Pre-requisites
We'll assume 3 things:
- That the model was created using the approach in this blog post.
- That the route was created using the approach in this blog post.
- 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());