Table of Contents
2. Define the Resource Structure
3. Use the Resource in a Controller
4. Working with Relationships (Nested Resources)
5. Conditional Attributes
6. Customize the Top-Level Response (Resource Collection)
Home PHP Framework Laravel How to use API resources in Laravel?

How to use API resources in Laravel?

Jul 27, 2025 am 04:09 AM

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.

How to use API resources in Laravel?

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.

How to use API resources in Laravel?

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:

How to use API resources in Laravel?
 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.

How to use API resources in Laravel?

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 [
            &#39;id&#39; => $this->id,
            &#39;title&#39; => $this->title,
            &#39;content&#39; => $this->content,
            &#39;created_at&#39; => $this->created_at->format(&#39;Ymd H:i:s&#39;),
            &#39;author&#39; => $this->whenLoaded(&#39;user&#39;, 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(&#39;user&#39;)->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 :

 &#39;author&#39; => new UserResource($this->whenLoaded(&#39;user&#39;)),

This keeps your response structured and reusable.


5. Conditional Attributes

Use when() to include fields conditionally:

 &#39;published_at&#39; => $this->when(!empty($this->published_at), $this->published_at),
&#39;views&#39; => $this->when($this->resource->relationLoaded(&#39;stats&#39;), $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([
        &#39;meta&#39; => [
            &#39;total_pages&#39; => $posts->lastPage(),
            &#39;current_page&#39; => $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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1511
276
What is Configuration Caching in Laravel? What is Configuration Caching in Laravel? Jul 27, 2025 am 03:54 AM

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.

Explain Laravel Eloquent Scopes. Explain Laravel Eloquent Scopes. Jul 26, 2025 am 07:22 AM

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.

How to mock objects in Laravel tests? How to mock objects in Laravel tests? Jul 27, 2025 am 03:13 AM

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

Using the Translator facade for Localization in Laravel. Using the Translator facade for Localization in Laravel. Jul 21, 2025 am 01:06 AM

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

How to create a helper file in Laravel? How to create a helper file in Laravel? Jul 26, 2025 am 08:58 AM

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

How to implement a referral system in Laravel? How to implement a referral system in Laravel? Aug 02, 2025 am 06:55 AM

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,

How to run a Laravel project? How to run a Laravel project? Jul 28, 2025 am 04:28 AM

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

How to seed a database in Laravel? How to seed a database in Laravel? Jul 28, 2025 am 04:23 AM

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

See all articles