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
Building an API Resource Class in Laravel
📖 Scenario: You are creating a simple API for a book store. You want to send book data in a clean and organized way to the users of your API.
🎯 Goal: Build a Laravel API resource class that formats book data with specific fields for API responses.
📋 What You'll Learn
Create a Book model with specific attributes
Create a BookResource API resource class
Format the resource to include only selected fields
Return the resource in a controller method
💡 Why This Matters
🌍 Real World
API resource classes help you send clean, consistent data from your Laravel backend to frontend apps or other services.
💼 Career
Understanding API resources is essential for backend developers working with Laravel to build APIs that frontend developers or mobile apps consume.
Progress0 / 4 steps
1
Create the Book model with attributes
Create a Laravel model called Book with these attributes: id, title, author, price, and published_year. Use an array called $fillable to allow mass assignment for title, author, price, and published_year.
Laravel
Hint
The $fillable array lets Laravel know which fields can be filled when creating or updating a model.
2
Create the BookResource API resource class
Create a Laravel API resource class called BookResource inside the App\Http\Resources namespace. Extend the JsonResource class.
Laravel
Hint
API resource classes extend JsonResource to format model data for JSON responses.
3
Define the toArray method to format book data
Inside the BookResource class, add a toArray method that returns an array with these keys and values: 'id' => $this->id, 'title' => $this->title, 'author' => $this->author, and 'year' => $this->published_year. Do not include the price field.
Laravel
Hint
The toArray method controls how the resource data is sent in the API response.
4
Return the BookResource from a controller method
In a controller method called show, return a single book wrapped in the BookResource. Use the variable $book as the model instance.
Laravel
Hint
Wrapping the model instance in the resource class formats the data automatically for the API response.
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
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.
Step 2: Identify what they do not do
They do not handle database migrations, authentication, or view rendering.
Final Answer:
To format and control the data sent in API responses -> Option C
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
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).
Step 2: Understand collection syntax
UserResource::collection($user) is for multiple models, not a single one.
Final Answer:
return new UserResource($user); -> Option A
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
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.
Step 2: Match output keys and values
Given id=5 and name='Alice', the JSON keys and values must match exactly as defined.
Final Answer:
{"user_id":5,"user_name":"Alice"} -> Option B
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
Step 1: Check toArray method return type
toArray should return an array, which Laravel converts to JSON automatically.
Step 2: Verify collection usage
Using ProductResource::collection($products) is the correct way to return multiple resources.
Final Answer:
The code is correct and will return a collection of formatted products -> Option A
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
Step 1: Understand conditional fields in API Resources
Laravel provides the 'when' helper to conditionally include fields in the response.
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.
Final Answer:
Use 'when' helper: 'is_admin' => $this->when($this->isAdmin(), true) -> Option D
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