Skip to main content

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 better code completion.


Using Resource in Controller

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.

  • Without Resource, we get an array like this [{...}, {...}, ...]
  • With Resource, we get an array like this {"data": [{...}, {...}, ...]}

The Full Lesson is Only for Premium Members

Want to access all of our courses? (36 h 00 min)

You also get:

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

Already a member? Login here

Randy Allen avatar

Great course so far, just a small thing I noticed, references to 'app/Http/Controllers/CategoryController' should be -> 'app/Http/Controllers/Api/CategoryController'

Modestas avatar

I just checked the code, and it should not have the /Api prefix since we are not using the prefix.

The reason for this is - we are building API only application. So there's no reason to add that prefix to namespace, since in our tutorial - we don't expect any non-api routes.

Randy Allen avatar

That makes sense, but in the first lesson this is the code ran that created the controller:

php artisan make:controller Api/CategoryController --resource --api --model=Category

Maybe I'm missing something but that makes this lessons references to app/Http/Controllers/CategoryController seem wrong. Either way, a minor detail, really enjoyed the course.

Modestas avatar

Whoops! I do need to adjust the command. Thanks for that!

And yes, it is minor, but does create confusion... Sorry!

Randy Allen avatar

No worries :) I figured I'd share because I know personally I'd want to fix it...cheers!

Modestas avatar

For sure! We sometimes miss things, so fixing them is a priority for us :) (also fixed the issue!)

Randy Allen avatar

It's easy to miss things like that for sure, I had to go back and check, command looks good...but the first lesson still references app/Http/Controllers/Api/CategoryController.php in a few places...sorry, the QA part of my brain can't help it :)

Modestas avatar

Fixed! Missed that file :(

Also, lovely QA part you have there!

Randy Allen avatar

Looks good! and thank you :) I think we've done enough for today, time to clockout

Jeff Collell avatar

Tutorial text mentions adding mixin annotation, but it's missing from code. Should be this:

/**

  • @mixin \App\Models\Category */ class CategoryResource extends JsonResource
Modestas avatar

Hi, thanks for letting me know. We are having issues with syntax highlighter and sometimes it hides full lines. Will fix this :)

Modestas avatar

Updated the lesson!

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.