patternphplaravelTip
API Resources for Consistent JSON Transformation
Viewed 0 times
api resourcejsontoArraywhenLoadeddata wrappingtransformationversioning
Problem
Returning Eloquent models directly from API controllers leaks internal field names, includes hidden fields if not set correctly, and makes it hard to version the API or add computed fields.
Solution
Use php artisan make:resource to generate API Resource classes. Define toArray() to explicitly declare every field returned. Use ResourceCollection for collections. Add conditional fields with $this->when() and conditional relations with $this->whenLoaded().
Why
Resources decouple the database schema from the API contract. Changes to column names only require updating the resource, not all consumers. $this->whenLoaded() prevents re-triggering N+1 queries.
Gotchas
- $this->whenLoaded('relation') returns null if the relation is not eager loaded—safe to use without triggering queries
- Wrap a single resource in a 'data' key automatically unless you use JsonResource::withoutWrapping()
- ResourceCollection has its own toArray() for the collection level metadata
- Avoid putting business logic or database calls inside toArray()—resources should be pure transformers
Code Snippets
API Resource with conditional relation
class PostResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'author' => new UserResource($this->whenLoaded('author')),
'published_at' => $this->published_at?->toIso8601String(),
];
}
}Revisions (0)
No revisions yet.