What are API resources
When building an API, returning Eloquent models directly as JSON can expose unwanted columns or send more data than the client needs. Eloquent API resources place a transformation layer between your models and JSON responses. ThetoArray() method lets you explicitly define what fields to include and in what format.
Key benefits:
- Full control over which fields appear in the response
- Field renaming and value formatting in one place
- Conditionally include or exclude fields
- Nest related resources for a consistent structure
Generating a resource
Use themake:resource Artisan command to generate a resource class.
app/Http/Resources.
$this because the resource proxies property access to the underlying model.
Returning a resource from a controller
Return the resource from a route or controller method.toResource() convenience method, which discovers the matching resource class by convention.
data key.
Resource collections
To return multiple models, use thecollection() method.
toResourceCollection() method.
Custom collection resource
When you need to add metadata to the entire collection, generate a dedicated collection resource.Transforming fields
Rename keys or transform values directly insidetoArray().
Conditional fields
when() — include a field based on a condition
Usewhen() to include a field only when a condition is true. When the condition is false, the key is removed entirely from the response.
mergeWhen() — conditionally merge multiple fields
When several fields share the same condition, usemergeWhen() to add them together.
whenLoaded() — include a relationship only when loaded
UsewhenLoaded() to avoid triggering unintended queries. The relationship is included only when it has already been eager-loaded.
whenCounted() — conditionally include a relationship count
Nested resources
Nest related resources to maintain a consistent response structure across your API.Adding metadata
with() — top-level metadata on a collection
Override thewith() method to add metadata returned only when the resource is the outermost response.
additional() — add metadata dynamically in the controller
Pagination
Pass a paginator to a resource collection and Laravel automatically appendsmeta and links to the response.
toResourceCollection() method.
Paginated responses always include the
data wrapper, even if you have called withoutWrapping(). This ensures the meta and links keys have a place to live alongside the data.Disabling data wrapping
By default, the outermost resource is wrapped in adata key. To disable this, call withoutWrapping() in AppServiceProvider.
Practical example: user API
The following example shows a complete user resource with an accompanying controller.UserResource
UserController
Related pages
Eloquent relationships
Learn how to define relationships and use eager loading.
Pagination
Combine pagination results with API resources.