Challenge - 5 Problems
API Resource Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this Laravel API Resource?
Given the following Laravel API Resource class, what will be the JSON output when returning
new UserResource($user) where $user has id=5, name='Alice', and email='alice@example.com'?Laravel
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { public function toArray($request) { return [ 'user_id' => $this->id, 'user_name' => $this->name, 'contact' => $this->email, ]; } }
Attempts:
2 left
💡 Hint
Look at the keys returned in the
toArray method and match them with the output.✗ Incorrect
The
toArray method defines the keys and values returned in the JSON. It renames the keys from the model's attributes to user_id, user_name, and contact.❓ lifecycle
intermediate1:30remaining
When is the
toArray method called in a Laravel API Resource?In Laravel API Resource classes, at what point is the
toArray method executed?Attempts:
2 left
💡 Hint
Think about when Laravel sends data to the browser or API client.
✗ Incorrect
Laravel calls
toArray automatically when the resource is serialized to JSON, such as when returning it from a controller or API route.📝 Syntax
advanced2:30remaining
Which option correctly adds a conditional attribute in a Laravel API Resource?
You want to include the
admin_notes attribute only if the user is an admin. Which code snippet inside toArray is correct?Attempts:
2 left
💡 Hint
Use Laravel's
when helper method correctly.✗ Incorrect
The
when method takes a condition first, then the value to include if true. Option A uses it correctly.🔧 Debug
advanced2:30remaining
Why does this Laravel API Resource return an empty JSON object?
Given this resource class, why does the API return
{} instead of user data?Laravel
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { public function toArray($request) { // Missing return statement [ 'id' => $this->id, 'name' => $this->name, ]; } }
Attempts:
2 left
💡 Hint
Check if the
toArray method returns the data.✗ Incorrect
Without a return statement, the method returns null, so Laravel outputs an empty JSON object.
🧠 Conceptual
expert2:00remaining
What is the main benefit of using Laravel API Resource classes?
Why should you use Laravel API Resource classes instead of returning Eloquent models directly in API responses?
Attempts:
2 left
💡 Hint
Think about data control and security in API responses.
✗ Incorrect
API Resource classes let you shape the JSON output and exclude fields you don't want to expose, improving security and flexibility.