0
0
Laravelframework~5 mins

Resource collections in Laravel

Choose your learning style9 modes available
Introduction

Resource collections help you turn many data items into a neat, consistent format. They make it easy to send lists of data in APIs.

When you want to send a list of users in a JSON response.
When you need to format multiple database records the same way.
When building an API that returns many items with the same structure.
When you want to add extra info to a group of resources before sending.
When you want to control how collections of data look in your app's output.
Syntax
Laravel
return UserResource::collection($users);
Use ::collection() on your resource class to wrap many items.
The resource class formats each item in the collection the same way.
Examples
This sends all users formatted by the UserResource.
Laravel
return UserResource::collection(User::all());
This adds extra meta info to the collection response.
Laravel
return PostResource::collection($posts)->additional(['meta' => ['count' => $posts->count()]]);
This sends paginated comments formatted by CommentResource.
Laravel
return CommentResource::collection($comments->paginate(10));
Sample Program

This example shows a UserResource that formats each user with id, name, and email. The controller returns all users wrapped in this resource collection, so the API response is a clean list of users.

Laravel
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}

// In a controller method:

use App\Models\User;
use App\Http\Resources\UserResource;

public function index()
{
    $users = User::all();
    return UserResource::collection($users);
}
OutputSuccess
Important Notes

Resource collections automatically wrap each item using the resource's toArray method.

You can add extra data to the whole collection using the additional() method.

Resource collections help keep your API responses consistent and easy to change later.

Summary

Resource collections format many items in the same way for API responses.

Use ::collection() on a resource class to wrap multiple models.

You can add extra info to collections with additional().