Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Creating Eloquent API Resource and Finishing CRUD

Premium
5 min read

In this lesson, we will take on two tasks:

  1. Implementing Laravel Eloquent API Resource
  2. Implementing CRUD operations for the Category model

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

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

LO
Liam Oliver ✓ Link copied!

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

M
Modestas ✓ Link copied!

Sorry about that, our highlighter removed the line! Fixed