🔴 Laravel Intermediate

What is API Resource in Laravel?

Why Interviewers Ask This

This question targets practical, hands-on experience with Laravel. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

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.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.