Laravel Best Practices
Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. For exact API syntax, verify with search-docs.
Consistency First
Before applying any rule, check what the application already does. Laravel offers multiple valid approaches — the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.
Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it — don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.
Quick Reference
1. Database Performance → rules/db-performance.md
- Eager load with
with() to prevent N+1 queries
- Enable
Model::preventLazyLoading() in development
- Select only needed columns, avoid
SELECT *
chunk() / chunkById() for large datasets
- Index columns used in
WHERE, ORDER BY, JOIN
withCount() instead of loading relations to count
cursor() for memory-efficient read-only iteration
- Never query in Blade templates
2. Advanced Query Patterns → rules/advanced-queries.md
addSelect() subqueries over eager-loading entire has-many for a single value
- Dynamic relationships via subquery FK +
belongsTo
- Conditional aggregates (
CASE WHEN in selectRaw) over multiple count queries
setRelation() to prevent circular N+1 queries
whereIn + pluck() over whereHas for better index usage
- Two simple queries can beat one complex query
- Compound indexes matching
orderBy column order
- Correlated subqueries in
orderBy for has-many sorting (avoid joins)
3. Security → rules/security.md
- Define
$fillable or $guarded on every model, authorize every action via policies or gates
- No raw SQL with user input — use Eloquent or query builder
{{ }} for output escaping, @csrf on all POST/PUT/DELETE forms, throttle on auth and API routes
- Validate MIME type, extension, and size for file uploads
- Never commit
.env, use config() for secrets, encrypted cast for sensitive DB fields
4. Caching → rules/caching.md
Cache::remember() over manual get/put
Cache::flexible() for stale-while-revalidate on high-traffic data
Cache::memo() to avoid redundant cache hits within a request
- Cache tags to invalidate related groups
Cache::add() for atomic conditional writes
once() to memoize per-request or per-object lifetime
Cache::lock() / lockForUpdate() for race conditions
- Failover cache stores in production
5. Eloquent Patterns → rules/eloquent.md
- Correct relationship types with return type hints
- Local scopes for reusable query constraints
- Global scopes sparingly — document their existence
- Attribute casts in the
casts() method
- Cast date columns, use Carbon instances in templates
whereBelongsTo($model) for cleaner queries
- Never hardcode table names — use
(new Model)->getTable() or Eloquent queries
6. Validation & Forms → rules/validation.md
- Form Request classes, not inline validation
- Array notation
['required', 'email'] for new code; follow existing convention
$request->validated() only — never $request->all()
Rule::when() for conditional validation
after() instead of withValidator()
7. Configuration → rules/config.md
env() only inside config files
App::environment() or app()->isProduction()
- Config, lang files, and constants over hardcoded text
8. Testing Patterns → rules/testing.md
LazilyRefreshDatabase over RefreshDatabase for speed
assertModelExists() over raw assertDatabaseHas()
- Factory states and sequences over manual overrides
- Use fakes (
Event::fake(), Exceptions::fake(), etc.) — but always after factory setup, not before
recycle() to share relationship instances across factories
9. Queue & Job Patterns → rules/queue-jobs.md
retry_after must exceed job timeout; use exponential backoff [1, 5, 10]
ShouldBeUnique to prevent duplicates; ShouldBeUniqueUntilProcessing for early lock release
- Always implement
failed(); with retryUntil(), set $tries = 0
RateLimited middleware for external API calls; Bus::batch() for related jobs
- Horizon for complex multi-queue scenarios
10. Routing & Controllers → rules/routing.md
- Implicit route model binding
- Scoped bindings for nested resources
Route::resource() or apiResource()
- Methods under 10 lines — extract to actions/services
- Type-hint Form Requests for auto-validation
11. HTTP Client → rules/http-client.md
- Explicit
timeout and connectTimeout on every request
retry() with exponential backoff for external APIs
- Check response status or use
throw()
Http::pool() for concurrent independent requests
Http::fake() and preventStrayRequests() in tests
12. Events, Notifications & Mail → rules/events-notifications.md, rules/mail.md
- Event discovery over manual registration;
event:cache in production
ShouldDispatchAfterCommit / afterCommit() inside transactions
- Queue notifications and mailables with
ShouldQueue
- On-demand notifications for non-user recipients
HasLocalePreference on notifiable models
assertQueued() not assertSent() for queued mailables
- Markdown mailables for transactional emails
13. Error Handling → rules/error-handling.md
report()/render() on exception classes or in bootstrap/app.php — follow existing pattern
ShouldntReport for exceptions that should never log
- Throttle high-volume exceptions to protect log sinks
dontReportDuplicates() for multi-catch scenarios
- Force JSON rendering for API routes
- Structured context via
context() on exception classes
14. Task Scheduling → rules/scheduling.md
withoutOverlapping() on variable-duration tasks
onOneServer() on multi-server deployments
runInBackground() for concurrent long tasks
environments() to restrict to appropriate environments
takeUntilTimeout() for time-bounded processing
- Schedule groups for shared configuration
15. Architecture → rules/architecture.md
- Single-purpose Action classes; dependency injection over
app() helper
- Prefer official Laravel packages and follow conventions, don't override defaults
- Default to
ORDER BY id DESC or created_at DESC; mb_* for UTF-8 safety
defer() for post-response work; Context for request-scoped data; Concurrency::run() for parallel execution
16. Migrations → rules/migrations.md
- Generate migrations with
php artisan make:migration
constrained() for foreign keys
- Never modify migrations that have run in production
- Add indexes in the migration, not as an afterthought
- Mirror column defaults in model
$attributes
- Reversible
down() by default; forward-fix migrations for intentionally irreversible changes
- One concern per migration — never mix DDL and DML
17. Collections → rules/collections.md
- Higher-order messages for simple collection operations
cursor() vs. lazy() — choose based on relationship needs
lazyById() when updating records while iterating
toQuery() for bulk operations on collections
18. Blade & Views → rules/blade-views.md
$attributes->merge() in component templates
- Blade components over
@include; @pushOnce for per-component scripts
- View Composers for shared view data
@aware for deeply nested component props
19. Conventions & Style → rules/style.md
- Follow Laravel naming conventions for all entities
- Prefer Laravel helpers (
Str, Arr, Number, Uri, Str::of(), $request->string()) over raw PHP functions
- No JS/CSS in Blade, no HTML in PHP classes
- Code should be readable; comments only for config files
How to Apply
Always use a sub-agent to read rule files and explore this skill's content.
- Identify the file type and select relevant sections (e.g., migration → §16, controller → §1, §3, §5, §6, §10)
- Check sibling files for existing patterns — follow those first per Consistency First
- Verify API syntax with
search-docs for the installed Laravel version
1---2name: laravel-best-practices3description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns."4license: MIT5metadata:6 source: https://skillmd.com/skills/coollabsio/laravel-best-practices7 author: laravel8---910# Laravel Best Practices1112Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. For exact API syntax, verify with `search-docs`.1314## Consistency First1516Before applying any rule, check what the application already does. Laravel offers multiple valid approaches — the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.1718Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it — don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.1920## Quick Reference2122### 1. Database Performance → `rules/db-performance.md`2324- Eager load with `with()` to prevent N+1 queries25- Enable `Model::preventLazyLoading()` in development26- Select only needed columns, avoid `SELECT *`27- `chunk()` / `chunkById()` for large datasets28- Index columns used in `WHERE`, `ORDER BY`, `JOIN`29- `withCount()` instead of loading relations to count30- `cursor()` for memory-efficient read-only iteration31- Never query in Blade templates3233### 2. Advanced Query Patterns → `rules/advanced-queries.md`3435- `addSelect()` subqueries over eager-loading entire has-many for a single value36- Dynamic relationships via subquery FK + `belongsTo`37- Conditional aggregates (`CASE WHEN` in `selectRaw`) over multiple count queries38- `setRelation()` to prevent circular N+1 queries39- `whereIn` + `pluck()` over `whereHas` for better index usage40- Two simple queries can beat one complex query41- Compound indexes matching `orderBy` column order42- Correlated subqueries in `orderBy` for has-many sorting (avoid joins)4344### 3. Security → `rules/security.md`4546- Define `$fillable` or `$guarded` on every model, authorize every action via policies or gates47- No raw SQL with user input — use Eloquent or query builder48- `{{ }}` for output escaping, `@csrf` on all POST/PUT/DELETE forms, `throttle` on auth and API routes49- Validate MIME type, extension, and size for file uploads50- Never commit `.env`, use `config()` for secrets, `encrypted` cast for sensitive DB fields5152### 4. Caching → `rules/caching.md`5354- `Cache::remember()` over manual get/put55- `Cache::flexible()` for stale-while-revalidate on high-traffic data56- `Cache::memo()` to avoid redundant cache hits within a request57- Cache tags to invalidate related groups58- `Cache::add()` for atomic conditional writes59- `once()` to memoize per-request or per-object lifetime60- `Cache::lock()` / `lockForUpdate()` for race conditions61- Failover cache stores in production6263### 5. Eloquent Patterns → `rules/eloquent.md`6465- Correct relationship types with return type hints66- Local scopes for reusable query constraints67- Global scopes sparingly — document their existence68- Attribute casts in the `casts()` method69- Cast date columns, use Carbon instances in templates70- `whereBelongsTo($model)` for cleaner queries71- Never hardcode table names — use `(new Model)->getTable()` or Eloquent queries7273### 6. Validation & Forms → `rules/validation.md`7475- Form Request classes, not inline validation76- Array notation `['required', 'email']` for new code; follow existing convention77- `$request->validated()` only — never `$request->all()`78- `Rule::when()` for conditional validation79- `after()` instead of `withValidator()`8081### 7. Configuration → `rules/config.md`8283- `env()` only inside config files84- `App::environment()` or `app()->isProduction()`85- Config, lang files, and constants over hardcoded text8687### 8. Testing Patterns → `rules/testing.md`8889- `LazilyRefreshDatabase` over `RefreshDatabase` for speed90- `assertModelExists()` over raw `assertDatabaseHas()`91- Factory states and sequences over manual overrides92- Use fakes (`Event::fake()`, `Exceptions::fake()`, etc.) — but always after factory setup, not before93- `recycle()` to share relationship instances across factories9495### 9. Queue & Job Patterns → `rules/queue-jobs.md`9697- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`98- `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release99- Always implement `failed()`; with `retryUntil()`, set `$tries = 0`100- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs101- Horizon for complex multi-queue scenarios102103### 10. Routing & Controllers → `rules/routing.md`104105- Implicit route model binding106- Scoped bindings for nested resources107- `Route::resource()` or `apiResource()`108- Methods under 10 lines — extract to actions/services109- Type-hint Form Requests for auto-validation110111### 11. HTTP Client → `rules/http-client.md`112113- Explicit `timeout` and `connectTimeout` on every request114- `retry()` with exponential backoff for external APIs115- Check response status or use `throw()`116- `Http::pool()` for concurrent independent requests117- `Http::fake()` and `preventStrayRequests()` in tests118119### 12. Events, Notifications & Mail → `rules/events-notifications.md`, `rules/mail.md`120121- Event discovery over manual registration; `event:cache` in production122- `ShouldDispatchAfterCommit` / `afterCommit()` inside transactions123- Queue notifications and mailables with `ShouldQueue`124- On-demand notifications for non-user recipients125- `HasLocalePreference` on notifiable models126- `assertQueued()` not `assertSent()` for queued mailables127- Markdown mailables for transactional emails128129### 13. Error Handling → `rules/error-handling.md`130131- `report()`/`render()` on exception classes or in `bootstrap/app.php` — follow existing pattern132- `ShouldntReport` for exceptions that should never log133- Throttle high-volume exceptions to protect log sinks134- `dontReportDuplicates()` for multi-catch scenarios135- Force JSON rendering for API routes136- Structured context via `context()` on exception classes137138### 14. Task Scheduling → `rules/scheduling.md`139140- `withoutOverlapping()` on variable-duration tasks141- `onOneServer()` on multi-server deployments142- `runInBackground()` for concurrent long tasks143- `environments()` to restrict to appropriate environments144- `takeUntilTimeout()` for time-bounded processing145- Schedule groups for shared configuration146147### 15. Architecture → `rules/architecture.md`148149- Single-purpose Action classes; dependency injection over `app()` helper150- Prefer official Laravel packages and follow conventions, don't override defaults151- Default to `ORDER BY id DESC` or `created_at DESC`; `mb_*` for UTF-8 safety152- `defer()` for post-response work; `Context` for request-scoped data; `Concurrency::run()` for parallel execution153154### 16. Migrations → `rules/migrations.md`155156- Generate migrations with `php artisan make:migration`157- `constrained()` for foreign keys158- Never modify migrations that have run in production159- Add indexes in the migration, not as an afterthought160- Mirror column defaults in model `$attributes`161- Reversible `down()` by default; forward-fix migrations for intentionally irreversible changes162- One concern per migration — never mix DDL and DML163164### 17. Collections → `rules/collections.md`165166- Higher-order messages for simple collection operations167- `cursor()` vs. `lazy()` — choose based on relationship needs168- `lazyById()` when updating records while iterating169- `toQuery()` for bulk operations on collections170171### 18. Blade & Views → `rules/blade-views.md`172173- `$attributes->merge()` in component templates174- Blade components over `@include`; `@pushOnce` for per-component scripts175- View Composers for shared view data176- `@aware` for deeply nested component props177178### 19. Conventions & Style → `rules/style.md`179180- Follow Laravel naming conventions for all entities181- Prefer Laravel helpers (`Str`, `Arr`, `Number`, `Uri`, `Str::of()`, `$request->string()`) over raw PHP functions182- No JS/CSS in Blade, no HTML in PHP classes183- Code should be readable; comments only for config files184185## How to Apply186187Always use a sub-agent to read rule files and explore this skill's content.1881891. Identify the file type and select relevant sections (e.g., migration → §16, controller → §1, §3, §5, §6, §10)1902. Check sibling files for existing patterns — follow those first per Consistency First1913. Verify API syntax with `search-docs` for the installed Laravel version