Bird
Raised Fist0
Laravelframework~10 mins

API resource classes 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 - API resource classes
Create Resource Class
↓
Define toArray()
↓
Controller returns Resource
↓
Resource transforms Model
↓
JSON Response Sent
This flow shows how Laravel API resource classes transform data models into JSON responses step-by-step.
Execution Sample
Laravel
class UserResource extends JsonResource {
  public function toArray($request) {
    return [
      'id' => $this->id,
      'name' => $this->name
    ];
  }
}
Defines a resource class that converts a User model into a simple JSON with id and name.
Execution Table
StepActionInputOutputNotes
1Create UserResource instanceUser model with id=5, name='Anna'UserResource wrapping User modelResource object created with model data
2Call toArray()UserResource instance{"id": 5, "name": "Anna"}Resource converts model to array
3Return Resource from ControllerUserResource instanceJSON response with {"id":5,"name":"Anna"}Laravel sends JSON response
4Client receives responseJSON responseParsed JSON objectClient can use data
💡 Response sent and client received JSON, process ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
User model{"id":5, "name":"Anna"}{"id":5, "name":"Anna"}{"id":5, "name":"Anna"}{"id":5, "name":"Anna"}{"id":5, "name":"Anna"}
UserResourcenullUserResource wrapping User modelUserResource wrapping User modelUserResource wrapping User modelnull (converted to JSON)
Array outputnullnull{"id":5,"name":"Anna"}{"id":5,"name":"Anna"}null (sent as JSON)
Key Moments - 3 Insights
Why do we use the toArray() method inside the resource class?
toArray() defines exactly how the model data is converted into an array for JSON output, as shown in step 2 of the execution_table.
Does the resource class modify the original model data?
No, the resource wraps the model and creates a new array representation without changing the original model, as seen in variable_tracker where the User model stays unchanged.
What happens if you return the model directly from the controller instead of the resource?
Returning the model directly sends all attributes without transformation or filtering, unlike the resource which controls output format (step 3 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of the toArray() method at step 2?
A{"id": 5, "name": "Anna"}
BUserResource instance
CJSON string
DUser model object
💡 Hint
Check the Output column at step 2 in the execution_table.
At which step does Laravel send the JSON response to the client?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for the step where the Output is described as JSON response in the execution_table.
If the toArray() method included an extra field 'email', how would the output at step 2 change?
AIt would remove 'name' from the output
BIt would cause an error
CIt would include 'email' in the array output
DIt would not change the output
💡 Hint
Refer to how toArray() defines the output array in the execution_table step 2.
Concept Snapshot
Laravel API Resource Classes:
- Create a resource class extending JsonResource
- Define toArray() to specify output fields
- Return resource from controller
- Laravel converts resource to JSON response
- Controls API output format cleanly
Full Transcript
Laravel API resource classes help convert data models into JSON responses for APIs. First, you create a resource class extending JsonResource. Inside, you define the toArray() method to specify which model fields to include in the output. When a controller returns this resource, Laravel calls toArray(), converts the result to JSON, and sends it as the API response. This process keeps your API output clean and consistent without changing the original model data.

Practice

(1/5)
1. What is the main purpose of an API Resource Class in Laravel?
easy
A. To manage user authentication
B. To handle database migrations
C. To format and control the data sent in API responses
D. To create views for web pages

Solution

  1. Step 1: Understand the role of API Resource Classes

    API Resource Classes in Laravel are designed to transform data models into JSON responses for APIs.
  2. Step 2: Identify what they do not do

    They do not handle database migrations, authentication, or view rendering.
  3. Final Answer:

    To format and control the data sent in API responses -> Option C
  4. Quick Check:

    API Resource Classes = Format API data [OK]
Hint: Remember: API Resource Classes shape API output data [OK]
Common Mistakes:
  • Confusing resource classes with controllers
  • Thinking resource classes handle database or auth
  • Assuming resource classes create HTML views
2. Which of the following is the correct way to return a single resource in a Laravel controller using an API Resource Class named UserResource?
easy
A. return new UserResource($user);
B. return UserResource::collection($user);
C. return UserResource::makeCollection($user);
D. return UserResource::toJson($user);

Solution

  1. Step 1: Recall syntax for returning a single resource

    To return a single model as a resource, you instantiate the resource class with the model: new UserResource($user).
  2. Step 2: Understand collection syntax

    UserResource::collection($user) is for multiple models, not a single one.
  3. Final Answer:

    return new UserResource($user); -> Option A
  4. Quick Check:

    Single resource = new Resource($model) [OK]
Hint: Use 'new Resource($model)' for single items [OK]
Common Mistakes:
  • Using collection() for single model
  • Calling non-existent methods like makeCollection()
  • Trying toJson() on resource class directly
3. Given the following Laravel API Resource class code, what will be the JSON output for a user with id=5 and name='Alice'?
class UserResource extends JsonResource {
    public function toArray($request) {
        return [
            'user_id' => $this->id,
            'user_name' => $this->name
        ];
    }
}

// In controller:
return new UserResource($user);
medium
A. {"id":5,"name":"Alice"}
B. {"user_id":5,"user_name":"Alice"}
C. {"userId":5,"userName":"Alice"}
D. {"user_id":5,"name":"Alice"}

Solution

  1. Step 1: Analyze the toArray method

    The method returns an array with keys 'user_id' and 'user_name' mapped to the model's id and name.
  2. Step 2: Match output keys and values

    Given id=5 and name='Alice', the JSON keys and values must match exactly as defined.
  3. Final Answer:

    {"user_id":5,"user_name":"Alice"} -> Option B
  4. Quick Check:

    toArray keys = JSON keys [OK]
Hint: Match keys exactly as returned in toArray() [OK]
Common Mistakes:
  • Assuming default keys like 'id' instead of 'user_id'
  • Mixing camelCase and snake_case keys
  • Ignoring the resource's toArray method
4. What is wrong with this Laravel API Resource class code snippet?
class ProductResource extends JsonResource {
    public function toArray($request) {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->price
        ];
    }
}

// In controller:
return ProductResource::collection($products);
medium
A. The code is correct and will return a collection of formatted products
B. Using ProductResource::collection is incorrect for multiple products
C. The controller should instantiate ProductResource with new keyword for collections
D. The toArray method should return a JSON string, not an array

Solution

  1. Step 1: Check toArray method return type

    toArray should return an array, which Laravel converts to JSON automatically.
  2. Step 2: Verify collection usage

    Using ProductResource::collection($products) is the correct way to return multiple resources.
  3. Final Answer:

    The code is correct and will return a collection of formatted products -> Option A
  4. Quick Check:

    collection() for multiple models = correct [OK]
Hint: Use ::collection() for multiple models, toArray returns array [OK]
Common Mistakes:
  • Expecting toArray to return JSON string
  • Using new keyword for collections
  • Confusing single resource and collection syntax
5. You want to add a conditional field is_admin to your UserResource that only appears if the user has admin rights. Which is the best way to do this in the toArray method?
hard
A. Add 'is_admin' => $this->isAdmin() ? true : false, unconditionally
B. Return two different resource classes for admin and non-admin users
C. Add 'is_admin' only if $this->isAdmin() is true by overriding toResponse()
D. Use 'when' helper: 'is_admin' => $this->when($this->isAdmin(), true)

Solution

  1. Step 1: Understand conditional fields in API Resources

    Laravel provides the 'when' helper to conditionally include fields in the response.
  2. Step 2: Evaluate options

    Use 'when' helper: 'is_admin' => $this->when($this->isAdmin(), true) uses 'when' correctly to include 'is_admin' only if the user is admin.
  3. Final Answer:

    Use 'when' helper: 'is_admin' => $this->when($this->isAdmin(), true) -> Option D
  4. Quick Check:

    Use when() for conditional fields [OK]
Hint: Use when() helper to add fields conditionally [OK]
Common Mistakes:
  • Always including the field even if false
  • Overriding toResponse unnecessarily
  • Creating separate resource classes for small condition