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...