How to use API resources in Laravel?
Using API resources is the recommended way to return structured JSON responses when building RESTful APIs in Laravel. 1. Use php artisan make:resource PostResource to create resource class; 2. Define return fields in the toArray method, such as id, title, created_at, etc.; 3. Return new PostResource($post) or PostResource::collection($posts); 4. Handle nested relationships through new UserResource($this->whenLoaded('user')); 5. Use the $this->when() condition to include fields to avoid returning null; 6. Add metadata through the additional() method, such as paging information; 7. Follow best practices, including preloading relationships, avoiding N 1 queries, and keeping resource logic concise. In this way, Laravel can automatically generate consistent and maintainable JSON responses, improve the readability and performance of the API, and ultimately achieve efficient data output.
Using API resources in Laravel is a clean and efficient way to transform your models and collections into JSON responses, especially when building RESTful APIs. Laravel's API resources help you control exactly what data is returned and how it's structured, making your responses consistent and maintainable.

Here's how to use API resources in Laravel:
1. Create an API Resource
First, generate a resource using Artisan. For a Post
model, run:

php artisan make:resource PostResource
This creates a PostResource
class in the app/Http/Resources
directory.
If you're working with a collection (eg, list of posts), Laravel also provides a way to handle that automatically.

You can also create a resource collection:
php artisan make:resource PostCollection
But as of Laravel 8 , ResourceCollection
is built into the base resource, so you usually just need one resource class.
2. Define the Resource Structure
Open app/Http/Resources/PostResource.php
. The toArray
method defines what data is included in the response.
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class PostResource extends JsonResource { public function toArray($request) { Return [ 'id' => $this->id, 'title' => $this->title, 'content' => $this->content, 'created_at' => $this->created_at->format('Ymd H:i:s'), 'author' => $this->whenLoaded('user', function () { return new UserResource($this->user); }), ]; } }
? Use
$this->whenLoaded()
to conditionally include relationships only if they're already loaded (to avoid N 1 queries).
3. Use the Resource in a Controller
In your controller, wrap the model or collection with the resource:
use App\Http\Resources\PostResource; use App\Models\Post; // Return a single post public function show(Post $post) { return new PostResource($post); } // Return a list of posts public function index() { return PostResource::collection(Post::with('user')->get()); }
Or with pagination (common in APIs):
public function index() { return PostResource::collection(Post::paginate(10)); }
Laravel automatically handles the pagination structure.
4. Working with Relationships (Nested Resources)
If your post has a user, create a UserResource
:
php artisan make:resource UserResource
Then use it inside PostResource
:
'author' => new UserResource($this->whenLoaded('user')),
This keeps your response structured and reusable.
5. Conditional Attributes
Use when()
to include fields conditionally:
'published_at' => $this->when(!empty($this->published_at), $this->published_at), 'views' => $this->when($this->resource->relationLoaded('stats'), $this->views),
This avoids sending null
values when data isn't relevant.
6. Customize the Top-Level Response (Resource Collection)
If you want to customize the wrapper (eg, add meta data), override the toResponse
method or use an anonymous resource collection.
For example, in a controller:
use Illuminate\Http\Resources\Json\AnonymousResourceCollection; public function index(): AnonymousResourceCollection { $posts = Post::paginate(10); return PostResource::collection($posts)->additional([ 'meta' => [ 'total_pages' => $posts->lastPage(), 'current_page' => $posts->currentPage(), ], ]); }
This adds extra info without creating a new resource class.
7. Best Practices
- Always eager load relationships used in resources to avoid performance issues.
- Use
whenLoaded()
for optional relationships. - Keep resource logic simple — don't put business logic inside.
- Use different resources for different API versions if needed (eg,
V1\PostResource
).
Using API resources in Laravel makes your API responses predictable and easy to maintain. You get full control over the output, and Laravel handles the JSON structure and status codes automatically.
Basically, wrap your models in resources, define the toArray()
method, and return them from controllers — that's it.
The above is the detailed content of How to use API resources in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

Laravel's EloquentScopes is a tool that encapsulates common query logic, divided into local scope and global scope. 1. The local scope is defined with a method starting with scope and needs to be called explicitly, such as Post::published(); 2. The global scope is automatically applied to all queries, often used for soft deletion or multi-tenant systems, and the Scope interface needs to be implemented and registered in the model; 3. The scope can be equipped with parameters, such as filtering articles by year or month, and corresponding parameters are passed in when calling; 4. Pay attention to naming specifications, chain calls, temporary disabling and combination expansion when using to improve code clarity and reusability.

UseMockeryforcustomdependenciesbysettingexpectationswithshouldReceive().2.UseLaravel’sfake()methodforfacadeslikeMail,Queue,andHttptopreventrealinteractions.3.Replacecontainer-boundserviceswith$this->mock()forcleanersyntax.4.UseHttp::fake()withURLp

TheTranslatorfacadeinLaravelisusedforlocalizationbyfetchingtranslatedstringsandswitchinglanguagesatruntime.Touseit,storetranslationstringsinlanguagefilesunderthelangdirectory(e.g.,en,es,fr),thenretrievethemviaLang::get()orthe__()helperfunction,suchas

Createahelpers.phpfileinapp/HelperswithcustomfunctionslikeformatPrice,isActiveRoute,andisAdmin.2.Addthefiletothe"files"sectionofcomposer.jsonunderautoload.3.Runcomposerdump-autoloadtomakethefunctionsgloballyavailable.4.Usethehelperfunctions

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

CheckPHP>=8.1,Composer,andwebserver;2.Cloneorcreateprojectandruncomposerinstall;3.Copy.env.exampleto.envandrunphpartisankey:generate;4.Setdatabasecredentialsin.envandrunphpartisanmigrate--seed;5.Startserverwithphpartisanserve;6.Optionallyrunnpmins

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4
