Keep Laravel API Responses Consistent with API Resources
A common Laravel API might start like this:
public function show(Post $post)
{
return response()->json($post);
}
It's simple.
But you're now returning the model's attributes directly.
As your application grows, you may want to:
- Rename fields
- Hide internal attributes
- Add calculated values
- Format dates
- Include relationships
This is where API Resources help.
Create a Resource
Create a resource with:
php artisan make:resource PostResource
Then define the response:
class PostResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'created_at' => $this->created_at?->toDateString(),
];
}
}
Now your API response is controlled by the Resource.
Return the Resource
Instead of:
return response()->json($post);
use:
return new PostResource($post);
For a collection:
return PostResource::collection($posts);
Hide Internal Fields
Suppose your posts table contains:
id
title
content
internal_notes
created_at
updated_at
You probably don't want:
internal_notes
in your public API.
With a Resource, simply don't include it:
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
];
Your database structure no longer has to match your API structure.
Add Calculated Data
You can also add values that aren't database columns:
return [
'id' => $this->id,
'title' => $this->title,
'reading_time' => $this->calculateReadingTime(),
];
This keeps your API response flexible without changing your database table.