Courses

[NEW] React Native Mobile App with Laravel 12 API

Creating Eloquent API Resource and Finishing CRUD

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Create Laravel API Resources to transform model data into consistent response formats
- Set up validation rules with Form Requests for storing and updating categories
- Implement complete CRUD operations in the CategoryController

Link to the repository

[Only for premium members]

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 19 text lessons of this course? (91 min read)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord