It is ok that we can create REST API in Laravel without using API resource and resource collection. But there is a beautiful feature in Laravel that you can use to build REST API in Laravel. When building an API, we may need a transformation layer that sits between our Eloquent models and the JSON responses that are actually returned to our application's users. In this case. we can use API resource in Laravel application.

In this tutorial, I will discuss laravel api resource example as well as laravel resource collection example. I will use the User model to transform our data into JSON responses using API resources. I will show you api resource laravel tutorial with JSON response. 

To create an API resource in Laravel, Laravel provides a command like the make:resource artisan command. So let's create a resource collection to transform our user list. So let's see how to create resource collections in Laravel:

php artisan make:resource UserCollection

 

This command will generate a user resource collection class like this:

App\Http\Resources\UserCollection .php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @return array<int|string, mixed>
     */
    public function toArray(Request $request): array
    {
        return parent::toArray($request);
    }
}

 

We will modify this toArray() method to transform our data layer with JSON response. So now create a route like this:

routes/api.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\UserController;

Route::controller(UserController::class)->group(function () {
    Route::get('user', 'index');
    Route::get('user/{user}', 'show');
});

 

Now update the UserController index method like that:

App\Http\Controllers\API\UserController.php

<?php

namespace App\Http\Controllers\API;

use App\Models\User;
use App\Http\Controllers\Controller;
use App\Http\Resources\API\UserCollection;

class UserController extends Controller
{
    public function index(User $user)
    {
        return new UserCollection($user->latest()->get());
    }
}

 

Now update the UserCollection class like below:

App\Http\Resources\UserCollection .php

<?php

namespace App\Http\Resources\API;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @return array<int|string, mixed>
     */
    public function toArray($request)
    {
        return [
            'data' => [
                'users' => $this->collection->map(function ($user) {
                    return [
                        'id'   => $user->id,
                        'name' => $user->name
                    ];
                })
            ]
        ];
    }

    public function with($request)
    {
        return [
            'isSuccess' => true
        ];
    }
}

 

Now if you visit the below URL to see the user list:

URL
http://127.0.0.1:8000/api/user

 

You will see the following json output like this:

{
  "data": {
    "users": [
      {
        "id": 1,
        "name": "Admin"
      }
    ]
  },
  "isSuccess": true
}

 

Read also: Lumen 10 JWT API Authentication Tutorial

 

Now assume we are going to show the single-user details. So there is also an artisan command and we need resources for that. So create it like the below command:

php artisan make:resource UserResource

 

Now update the controller for that:

App\Http\Controllers\API\UserController.php

<?php

namespace App\Http\Controllers\API;

use App\Models\User;
use App\Http\Controllers\Controller;
use App\Http\Resources\API\UserResource;

class UserController extends Controller
{
    public function show(User $user)
    {
        return new UserResource($user);
    }
}

 

Now update the UserResource like that:

App\Http\Resources\UserResource.php

<?php

namespace App\Http\Resources\API;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray($request)
    {
        return [
            'data' => [
                'user' => [
                    'id'   => $this->id,
                    'name' => $this->name,
                ]
            ]
        ];
    }

    public function with($request)
    {
        return [
            'isSuccess' => true
        ];
    }
}

 

Now if you visit the following URL:

URL
http://127.0.0.1:8000/api/user/1

 

You will see below output:

{
  "data": {
    "user": {
      "id": 1,
      "name": "Admin"
    }
  },
  "isSuccess": true
}

 

Read also: Laravel 10 JWT - Complete API Authentication Tutorial

 

Conclusion

Now we know How to create resource collections in Laravel. Now we also know laravel resource collection example. Hope laravel api resource example tutorial can help you to build your own api with laravel api resources and collection. Hope this how to use Laravel API resources tutorial will help you.

Category : #laravel

Tags : #laravel , #laravel api