When you want to create any APIs for web/mobile applications or any REST APIs, you must have to convert your response to a JSON object.

Let’s discuss how we can build API response through the Laravel Eloquent model with the relationship to arrays to JSON.

We’ve different types of processes in Laravel to make our response for APIs and for the frontend views.

Those are below:

1. By default Laravel Eloquent model provide the response in an object, and we need to convert it to the array and which will be passed through a Laravel response to the API as a JSON object.

For Ex.

$user = User::with('roles')->first();
return response ([
    'success' => true,
    'message' => 'User data with roles',
    'data' = [
        'user' => $user->toArray(),
    ]
], 200);

The same way we can get a response like this:

json_decode(User::with('roles')->get()->toJson(), true);

2. To pass a static collection in response to the API we can use the below process:
Ex.

$collection = collect([
    ‘f_name’ => fake()->firstName(),
    ‘l_name’ => fake()->lastName(),
]);
$collection->toArray();

3. After the Laravel 5.5 version release it provides us to convert our data (JSON/Array) easily as per our requirement. Laravel’s resource classes allow you to expressively and easily transform your models and model collections into JSON/Array.

To create a resource class, we need to run the below command:
Terminal command: php artisan make: resource UserResource

Resources extend the Illuminate\Http\Resources\Json\Resource class. Our UserResource will be like this:

<?php
 
namespace App\Http\Resources;
 
use Illuminate\Http\Resources\Json\Resource;
 
class UserResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

To, use this Resource and get the data:

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

public function index(){
    return new UserResource(User::find(1));
}

This will be useful for the single record to convert. To convert our full collection laravel provides us a facility to create a separate collection resource which will extend the Illuminate\Http\Resources\Json\ResourceCollection class.

Terminal command: php artisan make: resource User –collection / php artisan make:resource UserCollection

Through the use of UserCollection we can convert our full collection. We can pass other static parameters. Also, it’ll be like this:

<?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 [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}

To, use this Resource and get the data:

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

public function index(){
    return new UserCollection(User::all());
}

We can customise our UserResource as per our requirement to get a response as a JSON or Array. Use this type of Resource we don’t want to convert our record, It’ll be automatically converted. The benefits of using resources are:

  • We can use nested Resources/Collections
  • Convert relationship data into the Resource
  • To Getting data conditionally can be done easily
  • Pass our custom attributes with conditionally

So, you can convert your data as per your requirement with the use or ->toArray()/->toJson() and with the resource. But, the preferred way is to use Resource/Collection.

Support On Demand!

                                         
Laravel