Laravel Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
Laravel
- Authorize actions with policiesPermission checks are scattered across controllers and views and drift apart.
- Cache expensive data with stale-while-revalidateCache expiry causes a stampede of slow recomputations at the same moment.
- Call external APIs with timeouts, retries and fakesCalls to a partner API hang, fail on temporary errors, and make tests depend on the network.
- Catch N+1 queries with strict Eloquent modePages slow down as data grows because relations are lazy loaded in loops.
- Delete old records automatically with prunable modelsTables of logs, sessions and soft-deleted rows grow forever.
- Dispatch events and listeners after the transaction commitsListeners send emails or sync data for records that are then rolled back.
- Issue scoped API tokens with SanctumIntegrations need long-lived API access with limited permissions that can be revoked.
- Make queued jobs reliable with retries, backoff and uniquenessJobs fail on temporary errors, run twice for the same record, or hang forever.
- Prevent race conditions with transactions and row locksTwo requests redeem the same voucher or oversell the same stock.
- Rate limit routes per user and per IPLogin and public APIs are abused by scripts, and one heavy user slows everyone down.
- Respect third-party API rate limits in queued jobsA burst of jobs hits a partner API's rate limit and most of them fail.
- Reuse query logic with local scopesThe same where-clauses are copied across controllers and drift apart.
- Schedule tasks safely on multiple serversCron jobs run on every server, overlap with themselves, and fail silently.
- Send queued notifications over several channelsEmails slow down requests and users want some messages by Slack or SMS instead.
- Shape JSON responses with API ResourcesReturning models directly leaks columns and makes response formats drift.
- Use backed enums and casts on modelsStatuses are free-form strings with typos, and money or JSON columns need manual conversion.
- Validate requests with Form RequestsControllers fill up with validation and authorization code, and rules differ between create and update.
- Validate uploads and serve private files with temporary URLsUploads land on local disks, accept any file type, and private files are publicly accessible.
- Verify incoming webhook signaturesAnyone can POST fake events to the webhook endpoint.
- Write feature tests with fakesTests hit real queues and mail servers, or only test happy paths.