Laravel interview question · Most asked
What are API Resources and why use them?
Summary
API Resources (JsonResource) transform models into JSON in one place, controlling exactly which fields are exposed, formatting values, including relationships only when loaded, and wrapping collections with pagination metadata.
Longer Answer
Returning models directly (return $order;) exposes every visible column, including ones added later, and couples the API contract to the database schema. A resource declares the contract:
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'total' => $this->total_cents / 100,
'items' => OrderItemResource::collection($this->whenLoaded('items')),
'notes' => $this->when($request->user()->isStaff(), $this->notes),
];
}
whenLoaded avoids triggering lazy loads (N+1) from inside the resource; when/mergeWhen include fields conditionally. Resource collections add links and meta for paginated results.
Key Points
- Explicit, versionable JSON contract.
whenLoadedavoids N+1 in serialisation.- Conditional fields with
when. - Pagination metadata for collections.
More most-asked Laravel questions
- How do you validate requests in Laravel? Why use Form Requests?
- Gates or policies: how does authorization work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- How do queues work in Laravel?