API resource classes help you turn your data into a clean, easy-to-read format for apps to use. They make your API responses consistent and simple.
0
0
API resource classes in Laravel
Introduction
When you want to send data from your database to a mobile app in a neat format.
When you need to control which parts of your data are visible to users.
When you want to add extra information to your API responses, like links or metadata.
When you want to keep your API responses consistent across different parts of your app.
Syntax
Laravel
php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class YourResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, // add other fields here ]; } }
The toArray method defines how your data is shaped in the API response.
You extend JsonResource to create a resource class for your model.
Examples
This example shows a resource for a User model, returning id, email, and formatted creation date.
Laravel
php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'email' => $this->email, 'created_at' => $this->created_at->toDateString(), ]; } }
This example nests another resource (UserResource) for the post's author, showing how to include related data.
Laravel
php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class PostResource extends JsonResource { public function toArray($request) { return [ 'title' => $this->title, 'content' => $this->content, 'author' => new UserResource($this->whenLoaded('author')), ]; } }
Sample Program
This resource class formats a product's data. It shows the price with a dollar sign and checks if the product is in stock.
Laravel
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class ProductResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'price' => "$" . number_format($this->price, 2), 'in_stock' => $this->stock > 0, ]; } } // Usage in a controller method: // return new ProductResource(Product::find(1));
OutputSuccess
Important Notes
You can add conditional fields using $this->when() to show data only sometimes.
Use resource collections to return lists of resources easily.
Remember to load related data with with() in your queries to avoid extra database calls.
Summary
API resource classes format your data for clean API responses.
They help control what data your API sends out.
Use them to keep your API consistent and easy to maintain.