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.
  • whenLoaded avoids N+1 in serialisation.
  • Conditional fields with when.
  • Pagination metadata for collections.

Deep dive: Code Clinic: review a Laravel orders controller

More most-asked Laravel questions

← All Laravel questions