Beginner’s Guide to Laravel API Resource

Beginner's Guide to Laravel API Resource
Laravel API Resource

In this tutorial, we’ll learn what Laravel API Resources are, and how to use them in our Laravel project. We are going to create a user and post API resource in this project example.

Working with Laravel API Resource

For more, you can go and read the Laravel documentation about API resources.

Watch the video for more details.

Create User Resource

Resources are created on top of an eloquent model. So this means that we need to create a resource for every eloquent model separately.

To create a resource we need to run the following command on the terminal.

php artisan make:resource UserResource

This will create a new UserResource class in the application / Http / Resources. There all the Resources you create will reside.

If you open UserResource now, you will see that there is already a way to toArray. This is the method used to retrieve user-related data. By default, it simply returns the result of the toArray method to the user.

Learn more with free laravel full courses
Laravel Livewire tutorial
Laravel Inertia JS tutorial
Laravel roles and permission tutorial
Laravel testing tutorial

The current application model for which it is used, in this case, is the user model, represented within the field resource category in the classroom. Therefore, you can refer to the basic class with the $ this-> tool.

We will modify the returned Array list in User Resource to only restore the user id, name, and email conditionally if the user is admin and posts whenLoaded() the relationship. Change ToArray content to the following:

User Resource
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->when($this->is_admin, $this->email),
            'posts' => PostResource::collection($this->whenLoaded('posts'))
        ];
    }
}

Now create the post resource.

php artisan make:resource PostResource

We are going to modify the Post Resource to our needs.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'user' => new UserResource($this->whenLoaded('user'))
        ];
    }
}

Here we display only the id, title, and user whenLoaded() the user. You need to have relationship methods User with Post.

User model relationship method.

public function posts()
    {
        return $this->hasMany(Post::class);
    }

Post model relationship method.

public function user()
    {
        return $this->belongsTo(User::class);
    }

In the web.php routes, we are going to create these routes.

Route::get('/user/{id}', function ($id) {
    $user = User::with('posts')->findOrFail($id);
    return new UserResource($user);
});
Route::get('/{id}', function ($id) {
    $post = Post::with('user')->findOrFail($id);
    return new PostResource($post);
});
Route::get('/', function () {
    $posts = Post::with('user')->get();
    return PostResource::collection($posts);
});

Test the response on Insomnia or Postman

User/id endpoint
Laravel API resource

Here we get the user data with id which is the user id also the name and the posts that belong to this user. We don’t see the email here, because the user is not an admin.

Read Laravel 9 Mail Tutorial | How to Send Email
Admin endpoint
admin endpoint

The user with id 2 is admin so we see the email field here.

Posts endpoint
Posts endpoint

Here we see all the posts with the id, title, and the user to which the post belong.

Single post endpoint
single post endpoint

End the end we see the single post with the id, title, and the user.

Leave a Reply

Your email address will not be published.