Bird
Raised Fist0
Laravelframework~10 mins

Resource collections in Laravel - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Resource collections
Controller calls Resource Collection
↓
Resource Collection wraps Models
↓
Transforms each Model to JSON
↓
Returns JSON response to client
The controller uses a resource collection to wrap multiple models, transform each into JSON, and send the JSON response.
Execution Sample
Laravel
use App\Http\Resources\UserCollection;

public function index() {
  return new UserCollection(User::all());
}
This code returns a resource collection wrapping all User models, transforming them into JSON.
Execution Table
StepActionInputOutputNotes
1Controller calls UserCollectionUser::all() (list of users)UserCollection instanceWraps all users in collection
2UserCollection iterates modelsEach User modelCalls UserResource::toArray()Transforms each user
3UserResource transforms modelUser modelArray with selected fieldsE.g., id, name, email
4UserCollection gathers transformed arraysAll transformed user arraysArray of user arraysPrepares JSON structure
5UserCollection returns JSON responseArray of user arraysJSON response sent to clientFinal output
6Client receives JSONJSON responseReadable JSON dataCan be used by frontend or API consumer
💡 All users transformed and JSON response sent to client
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
usersemptyCollection of User modelsSame collection, iteratedIndividual user arraysArray of user arrays
resourceCollectionnullUserCollection instance wrapping usersSame instanceSame instanceJSON response
Key Moments - 3 Insights
Why does the controller return a UserCollection instead of raw User models?
Returning UserCollection ensures each User model is transformed consistently to JSON, as shown in execution_table step 2 and 3.
How does Laravel know which fields to include in the JSON?
The UserResource's toArray method defines which fields to include, referenced in execution_table step 3.
What happens if the collection is empty?
The UserCollection still returns an empty JSON array, as the iteration in step 2 has no models to transform.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 3?
AArray with selected user fields
BRaw User model
CUserCollection instance
DJSON response
💡 Hint
Check the 'Output' column in step 3 of execution_table
At which step does the JSON response get sent to the client?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look for 'returns JSON response' in the 'Action' column
If UserResource included a new field, how would the variable 'users' change after step 3?
AIt would remain as raw User models
BIt would include the new field in each user array
CIt would become a JSON string
DIt would be empty
💡 Hint
Refer to variable_tracker for 'users' after step 3 and execution_table step 3
Concept Snapshot
Resource collections wrap multiple models in Laravel.
They transform each model using a resource class.
The collection returns a JSON response.
Use in controllers to send consistent API data.
Empty collections return empty JSON arrays.
Full Transcript
In Laravel, resource collections help convert multiple models into JSON responses. The controller calls a resource collection with a list of models. The collection iterates over each model, transforming it using a resource class that defines which fields to include. Then, the collection gathers all transformed models into an array and returns it as a JSON response to the client. This process ensures consistent and clean API output. Even if the collection is empty, the response is a valid empty JSON array.

Practice

(1/5)
1. What is the primary purpose of using ::collection() in Laravel resource classes?
easy
A. To delete multiple records from the database
B. To create a single model instance
C. To format multiple model instances consistently in API responses
D. To validate incoming request data

Solution

  1. Step 1: Understand the role of resource collections

    Resource collections are used to format many items in the same way for API responses.
  2. Step 2: Identify what ::collection() does

    The ::collection() method wraps multiple model instances to apply the resource formatting to each item.
  3. Final Answer:

    To format multiple model instances consistently in API responses -> Option C
  4. Quick 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
A. return UserResource::collection($users);
B. return new UserResource($users);
C. return UserResource::make($users);
D. return UserResource::all($users);

Solution

  1. Step 1: Recall the syntax for resource collections

    To format multiple models, use ::collection() on the resource class with the collection as argument.
  2. Step 2: Match the syntax with options

    return UserResource::collection($users); uses UserResource::collection($users); which is correct. Other options either create a single resource or use invalid methods.
  3. Final Answer:

    return UserResource::collection($users); -> Option A
  4. Quick 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() or make()
  • 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
A. A plain array of user models without formatting
B. A JSON with only a 'meta' object and no user data
C. A JSON with a 'data' array but no meta information
D. A JSON with a 'data' array of users and a 'meta' object containing total count

Solution

  1. Step 1: Understand additional() method usage

    The additional() method adds extra data (like meta info) to the resource collection response.
  2. Step 2: Analyze the returned structure

    The response will have a data key with formatted users and a meta key with the total count from additional().
  3. Final Answer:

    A JSON with a 'data' array of users and a 'meta' object containing total count -> Option D
  4. Quick 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
A. Missing the collection argument inside collection()
B. Using additional() is not allowed on collections
C. Should use new UserResource() instead of collection()
D. The additional() method requires a string, not an array

Solution

  1. Step 1: Check the usage of collection()

    The collection() method requires a collection or array argument to wrap. Here it is called without any argument.
  2. Step 2: Validate other method usages

    additional() can be used on collections and accepts an array. Using new UserResource() is for single models, not collections.
  3. Final Answer:

    Missing the collection argument inside collection() -> Option A
  4. Quick 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
A. return PostResource::collection($posts->paginate(10))->additional(['meta' => ['current_page' => $posts->currentPage()]]);
B. return PostResource::collection($posts->paginate(10))->additional(['meta' => ['current_page' => $posts->paginate(10)->currentPage()]]);
C. return PostResource::collection($posts)->additional(['meta' => ['current_page' => $posts->currentPage()]]);
D. return new PostResource($posts->paginate(10))->additional(['meta' => ['current_page' => $posts->paginate(10)->currentPage()]]);

Solution

  1. Step 1: Understand pagination and resource collections

    When paginating, call paginate(10) on the query to get a paginator instance. Pass this to collection().
  2. Step 2: Access pagination info correctly

    To access currentPage(), it must be called on the paginator returned by paginate(), not on the original query builder $posts.
  3. Step 3: Identify correct option

    The snippet that calls $posts->paginate(10)->currentPage() within additional() correctly retrieves the current page from a paginator instance, ensuring the paginated data and meta align.
  4. Final Answer:

    return PostResource::collection($posts->paginate(10))->additional(['meta' => ['current_page' => $posts->paginate(10)->currentPage()]]); -> Option B
  5. Quick 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