Tuesday, 18 June 2024

Using the Eloquent API Resource to streamline data transferred by a Laravel 11 API Model


Eloquent is an Object-Relational Mapping (ORM) system that comes bundled with the Laravel PHP framework. It provides a simple and intuitive way to interact with your database using PHP. Eloquent allows you to define models, which are essentially classes that represent a single table in your database.

Pre-requisites

We'll assume 3 things:

  1. That the model was created using the approach in this blog post.
  2. That the route was created using the approach in this blog post.
  3. That a migration file has been set using this blog post.

Using the Eloquent API Resource to streamline data transferred by a Laravel 11 API Model

The Eloquent API Resource acts as a transformation layer between your eloquent models and the JSON responses. The object of this exercise is to specify only the fields we want to return to the requester, and contain the data within a data object.

To create an API resource run:

php artisan make:resource YourResource

Now the file is in the Resources directory.

Go to the Http/Resources/YourResource.php file

We will edit the function toArray()

This time we will return an associative array of fields e.g.

public function toArray(Request $request): array

{

return [

'id' => $this->id,            

'name' => $this->name,

// Note no description

        ];

}

Listing data using the API Resource

Our next step is to change the function index() in YourController.php, this time returning

YourResource::collection(YourModel::all());

No comments:

Post a Comment