UserResource::collection($users) where $users contains two users with names 'Alice' and 'Bob'?<?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); }
Laravel resource collections automatically wrap the array of transformed resources inside a data key. Each user is transformed using the UserResource toArray method, which returns username and email keys.
The collection method is a static method and should not be called with the new keyword. Option A incorrectly uses new with a static method call, causing a syntax error.
return UserResource::collection($users)->additional(['meta' => ['total_users' => $users->count()]]);What will be the value of the 'meta' key in the JSON response?
The additional method adds extra data to the resource response. Here, it adds a meta key with an array containing total_users equal to the count of users.
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?The response shows an empty 'data' array, indicating that $users is an empty collection. Even though active users exist, the query where('active', true) is likely incorrect (e.g., the column might be named 'is_active'), so no records match.
By default, Laravel resource collections wrap the array of transformed resources inside a data key. Pagination requires explicit use of pagination methods. Meta data can be added with the additional method. Manual looping is handled internally by the collection.