Laravel API Resources: Control Exactly What Your API Returns
Returning an Eloquent model straight from a controller works, but it exposes every column, ties your JSON to your database layout, and changes the moment you add a column. API resources are a thin layer that decides exactly what your API returns. This guide shows how to use them.
What this article is, and is not
This is a how-to based on documented Laravel behaviour. The examples use a posts API with authors and comments. There are no benchmarks in it.
The problem with returning models
return Post::find($id); // every column, including ones you never meant to expose
If you later add an internal_notes column, it appears in the response automatically. Hiding fields with $hidden helps, but it is a global setting for the model, not a per-endpoint decision.
Create a resource
php artisan make:resource PostResource
class PostResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'excerpt' => $this->excerpt,
'published' => $this->published_at?->toIso8601String(),
'author' => new UserResource($this->whenLoaded('author')),
'comments' => CommentResource::collection($this->whenLoaded('comments')),
];
}
}
Use it in a controller:
public function show(Post $post)
{
return new PostResource($post->load('author'));
}
public function index()
{
return PostResource::collection(Post::with('author')->paginate(15));
}
whenLoaded() avoids hidden queries
whenLoaded('author') includes the relationship only if you already loaded it. Without it, accessing $this->author inside the resource would run one query per item, which is the N+1 problem. Eager load in the controller, and let the resource include only what was loaded.
Conditional fields
'email' => $this->when($request->user()?->isAdmin(), $this->email),
The key is left out of the JSON entirely when the condition is false, rather than being returned as null.
Pagination comes for free
Passing a paginator to collection() adds links and meta sections to the response, with the current page, total and URLs for next and previous pages. Your client does not need custom code to build them.
The data wrapper
By default a resource wraps its output in a data key. That is useful, because you can add top-level fields later without breaking clients. You can remove the wrapper by calling JsonResource::withoutWrapping() in a service provider, but decide this early, because changing it later breaks existing clients.
Test the shape of the response
$this->getJson("/api/posts/{$post->id}")
->assertOk()
->assertJsonStructure(['data' => ['id', 'title', 'slug', 'excerpt']])
->assertJsonMissing(['internal_notes']);
Common mistakes
- Not eager loading, and so triggering a query for every item in a list.
- Returning dates in different formats from different endpoints. Choose one, such as ISO 8601.
- Letting a resource call another model's relationship that was never loaded.
- Changing field names in a published API without telling the people who depend on it.
Summary
One resource per model, eager load in the controller, whenLoaded() for relationships, and a test that asserts the structure so the shape cannot change by accident.