Laravel API Resources
Laravel API Resources: Tips & Tricks
Laravel API Resources: Tips & Tricks
Tip: Use whenLoaded() to Prevent N+1
public function toArray(Request $request): array
{
return [
'author' => new UserResource($this->whenLoaded('author')),
];
}
The author is only included if it was eager loaded.
Gotcha: Resources Don't Auto-Paginate
Resource::collection() returns all items. Use pagination on the query first:
return PostResource::collection(Post::paginate(10));
Tip: Conditional Attributes
'secret' => $this->when($request->user()->isAdmin(), $this->api_key),
Only includes the attribute when the condition is true.
Tip: Use additional() for Meta Data
return (new PostResource($post))
->additional(['meta' => ['version' => '2.0']]);
Gotcha: Resource Wrapping
By default, resources wrap output in a data key. Disable it:
Resource::withoutWrapping();
Or in AppServiceProvider::boot():
PostResource::withoutWrapping();
Tip: Merge Nested Resources
public function toArray(Request $request): array
{
return [
'id' => $this->id,
...$this->when($this->include_details, [
'details' => new DetailsResource($this),
]),
];
}
Tip: Use tap() for Quick Modifications
return tap(new PostResource($post), function ($resource) {
$resource->withComments = true;
});
Tip: Use route:cache Carefully
php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.
Tip: Model APP_KEY Rotation
Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.
Gotcha: Local Scope Leaks
Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.
Senior Insight
The deployment pipeline is where Laravel applications either thrive or suffer. I've standardized on a zero-downtime deployment process: build the application in a CI pipeline, run migrations before deploying code, use multiple servers behind a load balancer, and roll back by redeploying the previous version. The key insight: database migrations should always be backward-compatible. Never make a migration that breaks the old code — if the deployment fails halfway, you need the option to roll back without data loss.
Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)