Best Practice to Use API Resource Collection in Laravel

Hello Artisan,

When we build a frontend application using Laravel API, then we need to develop an API. We can develop API in the same way, but many developers return their JSON responses in their own way. So I am here to discuss how I return my API JSON response.

From this tutorial, you will learn the Laravel API resource tutorial and also I will show you the Laravel API resource collection example and how to use them. When do we need API resources? You know that sometimes we need to transform or change our API JSON response layer and you don't want to show your model structure to others, then we can use Laravel API resources and Laravel API resource collection.

Let assume we have a Category model and it has two fields like category_name and category_slug. Let's see the example that how we can transform or refactor our API response layer.

 

laravel-api-resource-tutorial

 

See the below example:

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Resources\CategoryCollection;

class CategoryController extends Controller
{
    public function index(Category $category)
    {   

        return response()->json([
            'isSuccess' => true,
            'data' => [
                'categories' => $category->latest()->get()
            ]
        ]);

    }
}

 

Look, it's the normal way we return our data. Now if we check it postman then the output will look like that:

{
    "isSuccess": true,
    "data": {
        "categories": [
            {
                "id": 1,
                "category_name": "at",
                "category_slug": "consequatur-accusamus-voluptatem-quasi-eaque",
                "created_at": "2021-11-26T07:34:51.000000Z",
                "updated_at": "2021-11-26T07:34:51.000000Z"
            },
            {
                "id": 2,
                "category_name": "consequatur",
                "category_slug": "magnam-voluptatem-temporibus-nostrum",
                "created_at": "2021-11-26T07:34:51.000000Z",
                "updated_at": "2021-11-26T07:34:51.000000Z"
            }
        ]
    }
}

 

Now assume we want to change this layer, what we can do? In this situation, we can use API resource collection. Just run below command to create a category resource collection to change this layer:

php artisan make:resource CategoryCollection

 

Now open this newly created API resource collection and update it like below:

Controller should be like that:

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Resources\CategoryCollection;

class CategoryController extends Controller
{
    public function index(Category $category)
    {   
        return new CategoryCollection($category->latest()->get());
    }
}

 

And the collection file will look like that:

App\Http\Resources\CategoryCollection.php

namespace App\Http\Resources;

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

class CategoryCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => [
                'categories' => $this->collection->map(function($data) {
                    return [
                        'id'         => $data->id,
                        'name'       => $data->category_name,
                        'slug'       => $data->category_slug,
                        'created_at'    => Carbon::parse($data->created_at)->toDateTimeString()
                    ];
                })
            ]
        ];
    }

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

 

Now our JSON response will look like that:

{
    "data": {
        "categories": [
            {
                "id": 1,
                "name": "at",
                "slug": "consequatur-accusamus-voluptatem-quasi-eaque",
                "created_at": "2021-11-26 07:34:51"
            },
            {
                "id": 2,
                "name": "consequatur",
                "slug": "magnam-voluptatem-temporibus-nostrum",
                "created_at": "2021-11-26 07:34:51"
            }
        ]
    },
    "isSuccess": true,
    "message": ""
}

 

That's the way we can use API resource collection in Laravel. Now let's see how we can use API resources only to show single object data in Laravel.

php artisan make:resource QuestionResource

 

Now update you show method like that:

public function show(Question $question)
{              
   return new QuestionResource($question);
}

 

Now open this newly created question resource to change its response layer:

App\Http\Resources\QuestionResource.php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class QuestionResource extends JsonResource
{
    
    public function toArray($request)
    {
        return [
            'data' => [
                'question' => [
                    'id'            => $this->id,
                    'title'         => $this->question_title,
                    'slug'          => $this->question_slug,
                    'details'       => $this->question_body,
                    'created'       => \Carbon\Carbon::parse($this->created_at)->toDayDateTimeString(),
                    'created_by'    => $this->user->name,
                    'category'      => $this->category->category_name,
                    'replies_count' => $this->replies->count(),
                ]
            ]
        ];
    }

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

 

Now if you check it via postman, then we will see the output like that:

{
    "data": {
        "question": {
            "id": 2,
            "title": "eos",
            "slug": "aut-quia-sint-et-eius-aut-illum",
            "details": "Corrupti voluptatibus qui labore vitae asperiores veniam illum.",
            "created": "Fri, Nov 26, 2021 7:34 AM",
            "created_by": "Ms. Kaia Crona IV",
            "category": "consequatur",
            "replies_count": 8
        }
    },
    "isSuccess": true,
    "message": ""
}

 

Read also: Building a REST API with Laravel Microservices Lumen

 

Hope this Laravel API resources and collection tutorial will help you to build API in the Laravel application. 

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js