Bird
Raised Fist0
Laravelframework~20 mins

Resource collections in Laravel - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Laravel Resource Collection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel resource collection?
Given the following Laravel resource collection code, what will be the JSON output when returning UserResource::collection($users) where $users contains two users with names 'Alice' and 'Bob'?
Laravel
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

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

// Controller method
public function index()
{
    $users = User::all();
    return UserResource::collection($users);
}
A{"data":[{"username":"Alice","email":"alice@example.com"},{"username":"Bob","email":"bob@example.com"}]}
B[{"username":"Alice","email":"alice@example.com"},{"username":"Bob","email":"bob@example.com"}]
C{"users":[{"name":"Alice","email":"alice@example.com"},{"name":"Bob","email":"bob@example.com"}]}
D{"data":{"username":"Alice","email":"alice@example.com"}}
Attempts:
2 left
💡 Hint
Remember that Laravel resource collections wrap the array of resources inside a 'data' key by default.
📝 Syntax
intermediate
1:30remaining
Which option causes a syntax error in Laravel resource collection usage?
Identify which code snippet will cause a syntax error when returning a resource collection in Laravel.
Areturn new UserResource::collection($users);
Breturn UserResource::collection($users)->response();
Creturn UserResource::collection($users);
Dreturn UserResource::collection($users)->toResponse($request);
Attempts:
2 left
💡 Hint
Check how the 'new' keyword is used with static methods.
❓ state_output
advanced
2:00remaining
What is the value of the 'meta' key in this resource collection response?
Consider this Laravel resource collection with added meta data:
return UserResource::collection($users)->additional(['meta' => ['total_users' => $users->count()]]);
What will be the value of the 'meta' key in the JSON response?
A[{"total_users":2}]
B{"total_users":2}
C{"count":2}
Dnull
Attempts:
2 left
💡 Hint
The additional method adds extra data at the root level of the JSON response.
🔧 Debug
advanced
2:30remaining
Why does this resource collection return an empty 'data' array?
Given this controller code:
public function index() {
    $users = User::where('active', true)->get();
    return UserResource::collection($users);
}
But the JSON response shows {"data":[]} even though there are active users in the database. What is the most likely cause?
AThe UserResource's toArray method returns an empty array.
BThe User model does not have an 'active' attribute.
CThe controller forgot to import the UserResource class.
DThe $users variable is empty because the query is incorrect.
Attempts:
2 left
💡 Hint
Consider why the query might not return the expected users.
🧠 Conceptual
expert
3:00remaining
Which statement about Laravel resource collections is TRUE?
Select the correct statement about Laravel resource collections.
AResource collections automatically paginate the data without extra code.
BResource collections require manual looping over each model to transform data.
CResource collections wrap the transformed data inside a 'data' key by default.
DResource collections cannot add extra meta data to the response.
Attempts:
2 left
💡 Hint
Think about the default JSON structure of resource collections.

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