In this lesson, we will take on two tasks:
- Implementing Laravel Eloquent API Resource
- Implementing CRUD operations for the
Categorymodel
At the end of this lesson, we will have a fully working CRUD for the Category model with transformed API responses:

Creating First Resource
Let's start by creating our first resource using the artisan command:
php artisan make:resource CategoryResourceThis 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...
Looks like the mixin annotation is missing in the snippet prior to: '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.'
Sorry about that, our highlighter removed the line! Fixed