Laravel 11 for Beginners: API Resources

Arlind Musliu Portrait
Arlind Musliu

July 29, 2024 · 4 min read · 69 views

Laravel Logo Post

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.

Understanding API Resources

API Resources in Laravel act as a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. They give you full control over the JSON structure returned by your API without having to modify your models.

Defining API Resources in Laravel

A resource class can be generated using the artisan command:

php artisan make:resource UserResource

The UserResource class is placed in the app/Http/Resources directory of your Laravel project.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            // You can include other model properties or even relationships
        ];
    }
}
?>

Using API Resources in Your Controllers

Once you have defined your API Resource, you can use it in your controllers to return model data. The API Resource will automatically convert the model into the JSON structure you defined in the toArray method.

Here's an example using the UserResource in a UserController:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Http\Resources\UserResource;

class UserController extends Controller
{
    public function show($id)
    {
		// Check if there is a user with that id
        $user = User::findOrFail($id);

        // Return a single user as a resource
        return new UserResource($user);
    }
}
?>

Laravel API Resource Collections

In addition to single resources, Laravel provides a convenient way to return collections of resources. You can use the UserResource::collection method to wrap a collection of models, applying the transformation to each item in the collection.

return UserResource::collection(User::paginate());

The above code will return a paginated list of users, each transformed by the UserResource.

API Resource for our Blog example

We will continue with our blog example and add the API routes.

Create API Resources

First, we need to create API Resources for our models. Open the terminal and run the following commands:

php artisan make:resource UserResource
php artisan make:resource PostResource

Define API Resources

Now, define the structure of each resource in the respective files located in app/Http/Resources.

UserResource.php

<?php
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'posts' => PostResource::collection($this->whenLoaded('posts')),
        ];
    }
}

PostResource.php

<?php
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'author' => new UserResource($this->whenLoaded('user')),
        ];
    }
}

Create an API Folder for Controllers

Create an API folder within the app/Http/Controllers directory to store your API controllers.

Create API Controllers

Generate the controllers and place them in the API folder:

php artisan make:controller API/UserController
php artisan make:controller API/PostController

Open each controller file and define the necessary methods using the API Resources.

API/UserController.php

<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        return UserResource::collection(User::all());
    }

    public function show($id)
    {
        $user = User::with('posts')->findOrFail($id);
        return new UserResource($user);
    }
}

API/PostController.php

<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Resources\PostResource;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        return PostResource::collection(Post::with('user', 'tags')->paginate());
    }

    public function show($id)
    {
        $post = Post::with('user', 'tags')->findOrFail($id);
        return new PostResource($post);
    }
}

Install API Routes

We need to install the API routes using the command below, and Laravel will handle the rest. It will install Laravel Sanctum for us and create the API route file in the routes folder, routes/api.php .

php artisan install:api

Update API Routes

Modify your routes/api.php file to use the new API controllers:

<?php
use App\Http\Controllers\API\UserController;
use App\Http\Controllers\API\PostController;

// User API routes
Route::get('/users', [UserController::class, 'index']);
Route::get('/users/{id}', [UserController::class, 'show']);

// Post API routes
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{id}', [PostController::class, 'show']);

Test Your API

For simplicity, we have kept these routes public and unprotected so you can test them easily. You can navigate to http://blog.test/api/users to see all the users registered in your app.

Alternatively, you can navigate to http://blog.test/api/users/1 to view the data for the user with ID 1.

However, you might want to protect your API routes and allow only certain apps to access them. We explain how to include middleware for route protection and how to install Laravel Sanctum to simplify the API process.

Conclusion

API Resources in Laravel provide a clean and fluent way to control the JSON output of your API. They allow you to shape your data precisely the way you want it, without cluttering your models or controllers with presentation logic. As you continue your journey with Laravel 11, mastering API Resources will be an essential skill for building modern and efficient APIs.

Upcoming Articles in the Series

  1. Laravel 11 for Beginners: API Routes with Laravel Sanctum

  2. Laravel 11 for Beginners: CSRF Protection explained

  3. Laravel 11 for Beginners: Using Helpers PHP functions

This article is part of our series Laravel 11 for Beginners: A Step-by-Step Guide to Learn the Concepts.


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!