Every Laravel API you have ever built has a moment of reckoning: the day a mobile app, a frontend, or a paying customer depends on the exact shape of your JSON, and you realise your controller is returning raw Eloquent models. Laravel API resources exist to stop that moment from becoming an incident. They are the transformation layer between your models and the JSON your clients actually receive, and once you use them properly, a database migration never leaks a column into production again. This guide walks through the whole system — single resources, collections, pagination, conditional fields, JSON:API resources, and versioning — with copy-paste code verified against the official Laravel 13.x documentation on 25 November 2026.
Why returning Eloquent models directly breaks your API
The shortcut looks harmless:
Route::get('/users/{id}', function (string $id) {
return User::findOrFail($id);
});
Laravel serialises the model to JSON and everything works — until it doesn’t. Add a column to the users table and it appears in the response overnight. A teammate adds a two_factor_secret or an internal notes field and it ships to every client. Rename a column and every consumer parsing the old key breaks at the same time. Your database schema and your public API contract are the same thing, and that is the bug.
A resource breaks the coupling. You declare exactly which fields leave your app, in what shape, and under what conditions. The model can change freely behind it. That is the whole idea, and everything else in this guide is a refinement of it.
Your first Laravel API resource
Generate a resource with Artisan. By default it lands in app/Http/Resources and extends Illuminate\Http\Resources\Json\JsonResource:
php artisan make:resource UserResource
Every resource defines a toArray() method that returns the array to convert to JSON. Inside it, you access model properties directly from $this — the resource proxies property and method access down to the underlying model:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
Return it from a route or controller by passing the model to its constructor:
use App\Http\Resources\UserResource;
use App\Models\User;
Route::get('/user/{id}', function (string $id) {
return new UserResource(User::findOrFail($id));
});
There is a shorter form. The model’s toResource() method discovers the resource by convention — it looks for a resource matching the model’s name, optionally suffixed with Resource, in the Http\Resources namespace closest to the model’s namespace:
return User::findOrFail($id)->toResource();
If your resource doesn’t follow the naming convention, or lives in a different namespace, you have two options: pass the class explicitly — ->toResource(CustomUserResource::class) — or pin it on the model with the #[UseResource(CustomUserResource::class)] attribute. The same pattern exists for collections with #[UseResourceCollection].
Laravel API resources and collections
A resource transforms one model. A resource collection transforms many, and can carry links and meta information that belong to the whole collection rather than one item. You rarely need a dedicated collection class — for a plain list, use the resource’s collection() method:
Route::get('/users', function () {
return UserResource::collection(User::all());
});
Or the Eloquent collection shortcut, which discovers the resource collection by convention:
return User::all()->toResourceCollection();
When you do need custom collection-level meta, generate a dedicated class. The --collection flag — or simply including the word Collection in the name — creates one extending ResourceCollection:
php artisan make:resource User --collection
php artisan make:resource UserCollection
class UserCollection extends ResourceCollection
{
public function toArray(Request $request): array
{
return [
'data' => $this->collection,
'links' => [
'self' => 'link-value',
],
];
}
}
Two details matter here. First, the collection’s $this->collection is automatically populated by mapping each item through the singular resource — UserCollection maps items through UserResource by convention, and you can override that with the #[Collects(Member::class)] attribute. Second, Laravel never double-wraps: if your collection already returns a data key, the framework won’t add another one.
One more behaviour to know: when a resource collection is returned from a route, Laravel resets the collection’s keys to numerical order. If your keys carry meaning — a collection keyed by user ID, for example — add the #[PreserveKeys] attribute to the resource class and the original keys survive.
The data wrapper and pagination
By default, your outermost resource is wrapped in a data key when the response is converted to JSON. If you would rather return the attributes at the top level, call JsonResource::withoutWrapping() — typically from your AppServiceProvider‘s boot() method. Note that it only affects the outermost response: data keys you add manually inside your own collections stay put.
Pagination is where resources really earn their keep. Pass a paginator to collection() or to a custom collection class and Laravel adds links and meta automatically — current page, total, per-page, and the first/last/prev/next URLs:
Route::get('/users', function () {
return new UserCollection(User::paginate());
});
// Or the convention shortcut:
return User::paginate()->toResourceCollection();
Paginated responses always contain meta and links, even if you called withoutWrapping(). If you want to change what those keys contain, define a paginationInformation() method on the resource — it receives the paginated data and the default links/meta array, and returns the modified version:
public function paginationInformation($request, $paginated, $default)
{
$default['links']['custom'] = 'https://example.com';
return $default;
}
Decide your pagination shape once and keep it identical across every endpoint. Clients write one parser for your API, not one per route — consistency here is worth more than any clever per-endpoint format.
Conditional attributes: show fields only when they should exist
Not every field belongs in every response. An admin-only field, a value that is expensive to compute, a field that only makes sense for some users — Laravel gives you a family of helpers for this, and they all work the same way: if the condition fails, the key is removed from the response entirely.
The when() method is the workhorse. Pass a condition and a value, or a closure if the value is expensive to calculate:
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'secret' => $this->when($request->user()->isAdmin(), 'secret-value'),
'secret' => $this->when($request->user()->isAdmin(), function () {
return 'secret-value';
}),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
Three companions cover the other cases. whenHas() includes an attribute only if it is actually present on the underlying model — useful when different queries select different columns. whenNotNull() includes it only when the value isn’t null. And when several attributes share one condition, mergeWhen() adds the whole group at once:
'name' => $this->whenHas('name'),
'nickname' => $this->whenNotNull($this->nickname),
$this->mergeWhen($request->user()->isAdmin(), [
'first-secret' => 'value',
'second-secret' => 'value',
]),
One warning from the docs: don’t use mergeWhen() inside arrays that mix string and numeric keys, or inside arrays with non-sequential numeric keys.
Conditional relationships and the N+1 trap
This is the section that saves you from the most common performance bug in Laravel APIs. If your resource accesses $this->posts directly, the relationship loads lazily — one extra query per item in a collection, the classic N+1 problem. The fix is to let the controller decide what to load and the resource include it only when it was loaded.
whenLoaded() takes the relationship name, not the relationship itself, so nothing is loaded just by checking:
'posts' => PostResource::collection($this->whenLoaded('posts')),
If the controller didn’t eager-load posts, the key is dropped from the response. Your controller stays in charge:
return new UserResource(User::with('posts')->findOrFail($id));
The same pattern covers counts and aggregates. Load the count in the controller with loadCount('posts'), then expose it with whenCounted(); use whenAggregated() for avg, sum, min, and max:
'posts_count' => $this->whenCounted('posts'),
'words_avg' => $this->whenAggregated('posts', 'words', 'avg'),
'words_sum' => $this->whenAggregated('posts', 'words', 'sum'),
For many-to-many pivot data, whenPivotLoaded() includes a value only when the pivot information is available — pass the pivot table name and a closure reading $this->pivot. If the relationship uses a custom intermediate table model, pass an instance of that model instead; if the pivot accessor isn’t pivot, use whenPivotLoadedAs().
The rule to internalise: a resource should never trigger a query. If a field needs data, the controller loads it and the resource conditionally includes it. That single discipline is what separates APIs that stay fast from APIs that quietly degrade as they grow.
Adding meta data: with() and additional()
Sometimes you need top-level data that describes the response as a whole — a rate-limit note, a version marker, a debug hint. There are two ways to add it, and they differ in scope.
The with() method lives on the resource class and only applies when the resource is the outermost resource being returned. That makes it the right place for response-level meta:
public function with(Request $request): array
{
return [
'meta' => [
'key' => 'value',
],
];
}
The additional() method is chained at the call site instead, when you’re constructing the resource in a route or controller:
return User::all()
->load('roles')
->toResourceCollection()
->additional(['meta' => [
'key' => 'value',
]]);
You can also add links directly in a collection’s toArray(). And if you’re worried about clashing with the paginator’s automatic links and meta keys — don’t be. Laravel merges your additional links with the paginator’s instead of overwriting them.
Customising the HTTP response itself
Resources control the body, but sometimes you need to control the response — status codes, cache headers, or deprecation warnings. There are two hooks.
Chain response() onto a resource at the call site. It returns a JsonResponse, giving you full control over headers:
Route::get('/user', function () {
return User::find(1)
->toResource()
->response()
->header('X-Value', 'True');
});
Or define a withResponse() method on the resource class itself. It runs when the resource is the outermost resource in a response:
public function withResponse(Request $request, JsonResponse $response): void
{
$response->header('X-Value', 'True');
}
This is the natural place for API versioning’s retirement warnings. When an old version is on its way out, send the standard Deprecation header (RFC 9745) and a Sunset date (RFC 8594) so clients notice before you switch the version off:
public function withResponse(Request $request, JsonResponse $response): void
{
$response->header('Deprecation', 'true');
$response->header('Sunset', 'Wed, 30 Jun 2027 00:00:00 GMT');
}
JSON:API resources in Laravel 13
If your clients expect strict JSON:API compliance, Laravel ships a dedicated resource class for it: JsonApiResource. It extends the standard JsonResource, handles the resource-object structure, relationships, sparse fieldsets, and includes, and sets the Content-Type header to application/vnd.api+json automatically.
Generate one with the --json-api flag:
php artisan make:resource PostResource --json-api
The generated class has $attributes and $relationships properties instead of a toArray() method. List attribute names to read them straight from the model, or override toAttributes() for full control — including closures for expensive attributes, which are only evaluated when actually needed:
class PostResource extends JsonApiResource
{
public $attributes = [
'title',
'body',
'created_at',
];
public $relationships = [
'author',
'comments',
];
}
Relationships are only serialised when the client asks for them via the include query parameter — GET /api/posts/1?include=author,comments — and the response carries resource identifier objects in relationships and full objects in a top-level included array. Nested includes work with dot notation (include=comments.author), with a default maximum depth you can raise via JsonApiResource::maxRelationshipDepth(3), typically in a service provider.
Clients can also request sparse fieldsets — only the attributes they need — with the fields parameter:
GET /api/posts?fields[posts]=title,created_at&fields[users]=name
And you can add per-resource links and meta with toLinks() and toMeta(). If you also need to parse incoming JSON:API query parameters such as filters and sorts, the docs point to Spatie’s Laravel Query Builder as the companion package.
Use JSON:API resources when your API has external consumers who expect the spec. For your own frontend or mobile app, plain resources are simpler and every bit as capable.
Versioning your API resources without duplicating your app
Laravel ships no built-in versioning system, so you pick a convention — and the one most teams land on is URL versioning (/api/v1/posts), because it’s visible in logs, easy to test in a browser, and trivial to cache. The key insight from the versioning guides is that you version the response, not the whole application.
Keep one model and one service layer. Give each version its own controllers and its own resources, in their own namespaces:
// routes/api.php
Route::prefix('v1')->name('v1.')->group(base_path('routes/api_v1.php'));
Route::prefix('v2')->name('v2.')->group(base_path('routes/api_v2.php'));
The name('v1.') prefix matters: without it, both versions register a route called users.show and php artisan route:cache fails with a duplicate-name error. Each version’s controller returns its own resource and calls the same underlying action or service — only the transformation differs.
One caveat with the toResource() shortcut: it finds resources by naming convention, mapping App\Models\Post to App\Http\Resources\PostResource. It won’t automatically find V1\PostResource, so versioned controllers should instantiate resources explicitly — new V1\PostResource($post) — or pass the class to toResource().
And be strict about what earns a new version. Adding a field, adding an endpoint, or adding an optional parameter is not breaking — existing clients ignore what they don’t know. Removing or renaming a field, changing a type, or changing the error format is breaking, and that is what a new version is for. When you do retire an old version, announce it with the Deprecation and Sunset headers from the previous section, and give clients a real migration window.
7 mistakes to avoid with Laravel API resources
1. Returning models directly. Every column you add later leaks into the response. A resource is the contract; treat it as one.
2. Accessing relationships without whenLoaded(). $this->posts inside a resource triggers a query per item in a collection. Use whenLoaded() and let the controller eager-load.
3. Leaking sensitive fields through parent::toArray(). The generated resource’s default toArray() returns every visible model attribute. Replace it with an explicit field list on day one.
4. Forgetting pagination meta. Clients need total, last_page, and the links to build a pager. Pass the paginator to the resource — don’t hand-roll pagination into the body.
5. Wrapping twice or not at all. Pick one shape — data wrapper or bare attributes — and keep it identical across every endpoint. withoutWrapping() is a global decision, not a per-route one.
6. Versioning the whole codebase. Duplicate controllers and services per version and you maintain two apps. Version the resources — the transformation layer — and share everything underneath.
7. Changing the error format in a minor release. Clients parse your error shape. Standardise it once (an RFC 7807-style type/title/status/detail shape works well), render it from the exception handler, and treat changing it as a breaking change.
The bottom line
Laravel API resources are a small amount of code for a large amount of safety. They decouple your database from your public contract, give you conditional fields and relationships that don’t cause N+1 queries, handle pagination meta for free, and — through versioned resources and deprecation headers — let you evolve an API without breaking the clients already using it. Start with one resource per model, keep whenLoaded() as a habit, and never return a bare model again.
All Laravel behaviour in this post was verified against the official Laravel 13.x Eloquent API Resources documentation on 25 November 2026.
Further Reading & References
- Eloquent: API Resources — Laravel 13.x Documentation (official docs; the source for every code example above)
- Laravel API Resources and Versioning: Clean REST APIs — LaraCopilot (Nov 2026 guide; Deprecation/Sunset headers,
toResource()versioning caveat) - Laravel API Versioning & Route Organization at Scale — DEV Community (one-file-per-version routing, route-name prefixes, per-version resources)
- Laravel API Versioning Strategies That Don’t Suck — DEV Community (version at the boundary, not the core; compatibility rules)
- Versioning a Laravel REST API Without Making a Mess — DEV Community (Nov 2026; what counts as breaking, RFC 7807 error shape, testing both versions)
- 10 Laravel REST API Best Practices for 2026 — Benjamin Crozat (version from day zero, form requests, resources, pagination)
- Laravel Resources and Collections: A Complete Guide to API Response Transformation — DEV Community
- Eloquent API Resources: Best Practices for Transforming Data in Laravel — DEV Community (conditional attributes,
whenLoaded()performance)
Related on HowToShipIt: Laravel Eloquent Relationships: The Complete Guide (2026) and Laravel Sanctum Setup: Complete Auth Guide (2026).



