Discover how to turn messy data loops into clean, reusable API responses effortlessly!
Why Resource collections in Laravel? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a list of users and you want to send their data as JSON in an API response. You write code to loop through each user and manually format each field.
Manually formatting each item is slow, repetitive, and easy to make mistakes. If you want to change the output format later, you must update every place you wrote the formatting code.
Laravel's resource collections let you define how a single item should look once, then automatically apply that format to every item in a list. This keeps your code clean and consistent.
foreach ($users as $user) { echo json_encode(['id' => $user->id, 'name' => $user->name]); }
return UserResource::collection($users);You can easily transform and customize large sets of data for APIs with minimal code and maximum consistency.
When building a user directory API, resource collections let you quickly return all users with the exact fields and format your frontend expects.
Manual data formatting is repetitive and error-prone.
Resource collections apply a single format to many items automatically.
This makes API responses consistent and easy to maintain.
Practice
::collection() in Laravel resource classes?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]
::collection() wraps many models for consistent output [OK]- Confusing
::collection()with single model resource - Thinking it deletes or modifies database records
- Mixing it up with validation methods
$users using a resource class UserResource?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]
::collection() for multiple items, not new [OK]- Using
new UserResource($users)for collections - Using non-existent methods like
all()ormake() - Confusing single resource and collection syntax
return UserResource::collection($users)->additional(['meta' => ['total' => $users->count()]]);
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]
additional() adds extra keys outside 'data' [OK]- Expecting meta inside each user item instead of outside
- Thinking additional() replaces data instead of adding
- Confusing plain arrays with resource formatted output
return UserResource::collection()->additional(['status' => 'success']);
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]
collection() [OK]- Calling
collection()without data - Thinking
additional()is invalid on collections - Confusing single resource and collection usage
meta key. Which code snippet correctly achieves this?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]
- Calling currentPage() on query builder $posts
- Passing unpaginated $posts to collection()
- Using new Resource() for paginated collections
