API resources
| 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