Complete the code to create a basic API resource class in Laravel.
use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->[1], 'email' => $this->email, ]; } }
The property name is the correct attribute to return the user's name in the resource.
Complete the code to return a collection of users using the resource class.
use App\Http\Resources\UserResource;
use App\Models\User;
public function index()
{
$users = User::all();
return UserResource::[1]($users);
}make which is for single models.all which is a query method, not a resource method.The collection method wraps a collection of models into a resource collection.
Fix the error in the resource class to correctly include a custom attribute.
class UserResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'is_admin' => $this->[1], ]; } }
The attribute is_admin matches the typical Laravel model attribute naming for boolean flags.
Fill both blanks to add a conditional attribute to the resource output.
class UserResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'email' => $this->email, 'phone' => $this->when($this->[1], $this->[2]), ]; } }
when method.The when method conditionally includes the phone attribute only if it is not null.
Fill all three blanks to customize the resource response with additional data and a custom key.
class UserResource extends JsonResource { public function toArray($request) { return [ '[1]' => $this->name, 'email' => $this->email, 'role' => $this->whenLoaded('[2]'), ]; } public function with($request) { return [ '[3]' => 'User data retrieved successfully', ]; } }
whenLoaded method properly.The key user_name customizes the name field key, role is the relation to load, and meta adds extra info to the response.