API Resources
What Is It?
API Resources transform Eloquent models into JSON responses with a consistent format. They act as a presentation layer for your API, decoupling the database schema from the response structure.
Why?
Returning raw Eloquent models as JSON exposes internal database columns and creates tight coupling between the API response and the database schema. Resources provide controlled, consistent output.
When to Use
For every API endpoint that returns model data. Resources ensure consistent response format, handle relationship nesting, and allow API evolution without database changes.
When Not to Use
For simple internal APIs with very few fields. For APIs consumed only by a single frontend where the contract is tightly controlled.
Example
Example
<?php
// API Resource
class PostResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'excerpt' => Str::limit(strip_tags($this->body), 150),
'body' => $this->when($request->routeIs('posts.show'), $this->body),
'author' => new UserResource($this->whenLoaded('user')),
'tags' => TagResource::collection($this->whenLoaded('tags')),
'comments_count' => $this->whenCounted('comments'),
'is_mine' => $this->whenAuthenticated(fn () => $this->user_id === auth()->id()),
'published_at' => $this->published_at?->toIso8601String(),
'created_at' => $this->created_at->toIso8601String(),
];
}
}
// Collection resource
class PostCollection extends JsonResource
{
public function toArray(Request $request): array
{
return [
'data' => $this->collection,
'meta' => [
'total' => $this->total(),
'per_page' => $this->perPage(),
'current_page' => $this->currentPage(),
],
];
}
}
// Usage in controller
public function index()
{
return new PostCollection(
Post::with(['user', 'tags'])->paginate(15)
);
}
Pros
- Consistent API response format
- Decoupled from database schema
- Handles relationships cleanly
- Conditionally includes fields
- Easy to version and evolve APIs
Cons
- Adds a layer between model and response
- Can lead to resource proliferation
- May duplicate transformation logic
- Learning curve for complex resources