Using API Resources and Resource Collections
Returning an Eloquent model directly from a controller exposes every column, including ones you may not want clients to see. Laravel's API Resources solve this by giving a dedicated transformation layer between models and JSON output.
Generating a Resource
php artisan make:resource PostResource
This creates a class in app/Http/Resources with a toArray() method where the exact output shape is defined.
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'excerpt' => Str::limit($this->body, 100),
'published_at' => $this->created_at->toDateString(),
];
}
Resource Collections
When returning many records, a Resource Collection wraps each item with the resource's transformation and adds a data key automatically.
return PostResource::collection(Post::all());
Why This Matters
- Hides internal or sensitive attributes from API consumers
- Lets the same model be shaped differently for different endpoints
- Centralizes formatting logic (dates, currency, nested relationships) in one place
With clean, predictable output in place, attention usually turns to controlling who is allowed to call these endpoints at all.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.
