API resources

Contents
A Resource class
Shape with toArray
Collections
When resources win

A Resource class

Models carry hidden fields and odd shapes that APIs should not leak. A Resource class sits between the model and the JSON answer.

Create one Resource per model and keep every output change in that one place.

class UserResource extends JsonResource { public function toArray($request) { return [ "id" => $this->id, "name" => $this->name, ]; } }

Shape with toArray

toArray picks which fields leave the server and under which names. Return plain values only, so the output stays JSON friendly.

Rename odd columns here instead of in every controller.

return [ "id" => $this->id, "email" => $this->email, ];

Collections

Lists need the same shape applied to every row. The collection helper wraps many models in the same Resource with one call.

Paginate first for large tables, then wrap the page before returning it.

return UserResource::collection($users);

When resources win

Small prototypes can return models directly, but growing APIs outgrow that fast. Reach for resources when fields must hide, names must stay stable, or versions diverge.

One Resource per answer keeps clients calm across releases.

return new UserResource($user);

Next: Gates and policies

Article author: Arthur Isaev

Related articles
Development with PHP
What is Laravel and where it runs
Install Laravel
Your first route
Controllers
Blade basics
Blade advanced
Migrations
Eloquent models
Relationships
Query builder
Seeders and factories
Validation
Auth intro
Hand-rolled login
Middleware
Service container
Config and env
Artisan commands
Events and listeners
Queues
Mail
Cache
Sessions in Laravel
CSRF
Hashing
Sanctum tokens
API resources
Gates and policies
Notifications
Scheduler
Filesystem
Localization
Testing
HTTP tests
Collections
Carbon dates
Pagination
File uploads
Eloquent advanced
Transactions and locks
Deployment
Debugbar and dd
Broadcasting
Full-text search
Capstone: blog
Capstone: JSON API
Capstone: shop cart
Performance: kill N+1
Modern Laravel tour
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: