🔴 Laravel
Intermediate
What is API Resource in Laravel?
Answer
API Resources (Laravel 5.5+) provide a transformation layer between Eloquent models and JSON responses, giving you full control over what is included and how data is formatted. Generate: php artisan make:resource UserResource. In the toArray() method, define the JSON structure: return ["id" => $this->id, "name" => $this->name, "email" => $this->email, "role" => $this->whenLoaded("role")]. Use: return new UserResource($user) or for collections: return UserResource::collection(User::paginate(15)). Conditional fields: $this->when($this->isAdmin(), "admin_data"). Load relationships only if already eager-loaded: $this->whenLoaded("posts") — prevents N+1 in APIs. Resource collections support custom wrapper keys and meta data.