Link to the repository
[Only for premium members]
[Only for premium members]
In this lesson, we will take on two tasks:
Category
modelAt the end of this lesson, we will have a fully working CRUD for the Category
model with transformed API responses:
Let's start by creating our first resource using the artisan command:
php artisan make:resource CategoryResource
This will create a scaffold for our resource:
app/Http/Resources/CategoryResource.php
use Illuminate\Http\Request;use Illuminate\Http\Resources\Json\JsonResource; class CategoryResource extends JsonResource{ /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return parent::toArray($request); }}
Here, we should focus on the toArray
method. This is where we can transform our model data into the desired format. So let's add our transformation logic:
app/Http/Resources/CategoryResource.php
use App\Models\Category;use Illuminate\Http\Request;use Illuminate\Http\Resources\Json\JsonResource; class CategoryResource extends JsonResource{ /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return parent::toArray($request); return [ 'id' => $this->id, 'name' => $this->name, ]; }}
We have also added a mixing annotation to the class. This will help IDE to understand that this resource is related to the Category
model and provide better code completion.
The last thing we must do is use this resource in our Controller. Let's update our CategoryController
:
app/Http/Controllers/CategoryController.php
use App\Http\Resources\CategoryResource;// ... public function index(){ return CategoryResource::collection(Category::all());}
Now, if we run our Postman request, we should see the transformed response:
If we need to add more fields to the response, we can easily do that by updating the CategoryResource
class:
app/Http/Resources/CategoryResource.php
return [ 'id' => $this->id, 'name' => $this->name, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at,];
Now our response will include created_at
and updated_at
fields as well:
This is a great way to keep our API responses consistent and clean.
Note: Remember to remove the created_at
and updated_at
fields, which are an example of how to add more fields to the response.
Another thing you might have noticed is that we have a difference in response structure.
[{...}, {...}, ...]
{"data": [{...}, {...}, ...]}