Resource collections help you turn many data items into a neat, consistent format. They make it easy to send lists of data in APIs.
Resource collections in Laravel
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
UserResource.Laravel
return UserResource::collection(User::all());Laravel
return PostResource::collection($posts)->additional(['meta' => ['count' => $posts->count()]]);
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); }
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().
Practice
1. What is the primary purpose of using
::collection() in Laravel resource classes?easy
Solution
Step 1: Understand the role of resource collections
Resource collections are used to format many items in the same way for API responses.Step 2: Identify what
The::collection()does::collection()method wraps multiple model instances to apply the resource formatting to each item.Final Answer:
To format multiple model instances consistently in API responses -> Option CQuick Check:
Resource collections format many items = A [OK]
Hint: Remember:
::collection() wraps many models for consistent output [OK]Common Mistakes:
- Confusing
::collection()with single model resource - Thinking it deletes or modifies database records
- Mixing it up with validation methods
2. Which of the following is the correct syntax to return a resource collection for a list of users stored in
$users using a resource class UserResource?easy
Solution
Step 1: Recall the syntax for resource collections
To format multiple models, use::collection()on the resource class with the collection as argument.Step 2: Match the syntax with options
return UserResource::collection($users); usesUserResource::collection($users);which is correct. Other options either create a single resource or use invalid methods.Final Answer:
return UserResource::collection($users); -> Option AQuick Check:
Correct syntax for collections = D [OK]
Hint: Use
::collection() for multiple items, not new [OK]Common Mistakes:
- Using
new UserResource($users)for collections - Using non-existent methods like
all()ormake() - Confusing single resource and collection syntax
3. Given the following code, what will be the output structure of the API response?
return UserResource::collection($users)->additional(['meta' => ['total' => $users->count()]]);
medium
Solution
Step 1: Understand
Theadditional()method usageadditional()method adds extra data (like meta info) to the resource collection response.Step 2: Analyze the returned structure
The response will have adatakey with formatted users and ametakey with the total count fromadditional().Final Answer:
A JSON with a 'data' array of users and a 'meta' object containing total count -> Option DQuick Check:
Collection + additional meta = data + meta JSON [OK]
Hint: Remember
additional() adds extra keys outside 'data' [OK]Common Mistakes:
- Expecting meta inside each user item instead of outside
- Thinking additional() replaces data instead of adding
- Confusing plain arrays with resource formatted output
4. Identify the error in the following code snippet that tries to return a resource collection:
return UserResource::collection()->additional(['status' => 'success']);
medium
Solution
Step 1: Check the usage of
Thecollection()collection()method requires a collection or array argument to wrap. Here it is called without any argument.Step 2: Validate other method usages
additional()can be used on collections and accepts an array. Usingnew UserResource()is for single models, not collections.Final Answer:
Missing the collection argument insidecollection()-> Option AQuick Check:
collection()needs argument [OK]
Hint: Always pass your data to
collection() [OK]Common Mistakes:
- Calling
collection()without data - Thinking
additional()is invalid on collections - Confusing single resource and collection usage
5. You want to return a paginated list of posts with a resource collection and include extra pagination info under a
meta key. Which code snippet correctly achieves this?hard
Solution
Step 1: Understand pagination and resource collections
When paginating, callpaginate(10)on the query to get a paginator instance. Pass this tocollection().Step 2: Access pagination info correctly
To accesscurrentPage(), it must be called on the paginator returned bypaginate(), not on the original query builder$posts.Step 3: Identify correct option
The snippet that calls$posts->paginate(10)->currentPage()withinadditional()correctly retrieves the current page from a paginator instance, ensuring the paginated data and meta align.Final Answer:
return PostResource::collection($posts->paginate(10))->additional(['meta' => ['current_page' => $posts->paginate(10)->currentPage()]]); -> Option BQuick Check:
paginate() result for both collection and currentPage() [OK]
Hint: Access pagination methods on paginate() result, not query builder [OK]
Common Mistakes:
- Calling currentPage() on query builder $posts
- Passing unpaginated $posts to collection()
- Using new Resource() for paginated collections
