laravel-best-practices
Skill2 starsChanged 3 months agoMITView on GitHub
Use when writing, reviewing, or refactoring Laravel PHP code, including Eloquent, controllers, validation, authorization, queues, migrations, and queries.
- Reads credentials
33 other projects use a version of this, 29 of them edited.
Adopted by
Most recently taken up by
- ownego/token-slayeredited, first seen Nov 8, 2026
- rbaskam/PRismedited, first seen Nov 1, 2026
- pablopetr/claude-skillstheir own version, first seen Oct 25, 2026
- davidanthonyn/claude-skillstheir own version, first seen Oct 20, 2026
- PauloFelipeM/agent-laravel-skillstheir own version, first seen Oct 9, 2026
- RiprLutuk/PasPapanedited, first seen Oct 8, 2026
Used with
Projects with it also use socialite-development, inertia-vue-development and 9 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
ownegoSkillsocialite-development
Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication.
Also in 11 projects that use this
syofyanzuhadSkillinertia-vue-development
Develops Inertia.js v2 Vue client-side applications. Activates when creating Vue pages, forms, or navigation; using <Link>, <Form>, useForm, or router; working with deferred props, prefetching, or polling; or when user mentions Vue with Inertia, Vue pages, Vue forms, or Vue navigation.
Also in 7 projects that use this
syofyanzuhadSkillwayfinder-development
Use this skill for Laravel Wayfinder which auto-generates typed functions for Laravel controllers and routes. ALWAYS use this skill when frontend code needs to call backend routes or controller actions. Trigger when: connecting any React/Vue/Svelte/Inertia frontend to Laravel controllers, routes, building end-to-end features with both frontend and backend, wiring up forms or links to backend endpoints, fixing route-related TypeScript errors, importing from @/actions or @/routes, or running wayfinder:generate. Use Wayfinder route functions instead of hardcoded URLs. Covers: wayfinder() vite plugin, .url()/.get()/.post()/.form(), query params, route model binding, tree-shaking. Do not use for backend-only task
Also in 5 projects that use this
datashamanSkillpassport-development
Develops OAuth2 API authentication with Laravel Passport. Activates when installing or configuring Passport; setting up OAuth2 grants (authorization code, client credentials, personal access tokens, device authorization); managing OAuth clients; protecting API routes with token authentication; defining or checking token scopes; configuring SPA cookie authentication; handling token lifetimes and refresh tokens; or when the user mentions Passport, OAuth2, API tokens, bearer tokens, or API authentication. Make sure to use this skill whenever the user works with OAuth2, API tokens, or third-party API access, even if they don't explicitly mention Passport.
Also in 7 projects that use this
ownegoSkilllivewire-development
Use for any task or question involving Livewire. Activate if user mentions Livewire, wire: directives, or Livewire-specific concepts like wire:model, wire:click, wire:sort, or islands, invoke this skill. Covers building new components, debugging reactivity issues, real-time form validation, drag-and-drop, loading states, migrating from Livewire 3 to 4, converting component formats (SFC/MFC/class-based), and performance optimization. Do not use for non-Livewire reactive UI (React, Vue, Alpine-only, Inertia.js) or standard Laravel forms without Livewire.
Also in 9 projects that use this
datashamanSkillconfiguring-horizon
Use this skill whenever the user mentions Horizon by name in a Laravel context. Covers the full Horizon lifecycle: installing Horizon (horizon:install, Sail setup), configuring config/horizon.php (supervisor blocks, queue assignments, balancing strategies, minProcesses/maxProcesses), fixing the dashboard (authorization via Gate::define viewHorizon, blank metrics, horizon:snapshot scheduling), and troubleshooting production issues (worker crashes, timeout chain ordering, LongWaitDetected notifications, waits config). Also covers job tagging and silencing. Do not use for generic Laravel queues without Horizon, SQS or database drivers, standalone Redis setup, Linux supervisord, Telescope, or job batching.
Also in 10 projects that use this
- +1 more from syofyanzuhad
- +1 more from ownego
Other versions33 projects use a version of this.
Word for word · 0
None found.
Edited · 29
- coollabsio/coolify★ 66k13% same
- anonaddy/anonaddy★ 4.9k13% same
- yaojingang/GEOFlow★ 4k13% same
- Relaticle/relaticle★ 1.8k13% same
- relaticle/relaticle★ 1.8k13% same
- nasirkhan/laravel-starter★ 1.4k13% same
- Blair2004/NexoPOS★ 1.3k90% same
- whisper-money/whisper-money★ 1.1k13% same
- WINBIGFOX/TimeScribe★ 93311% same
- m3ue/m3u-editor★ 88990% same
19 more not listed
Wrote their own version · 4
- PauloFelipeM/agent-laravel-skills★ 14same name
- robiparvez/claude-code-guidelines★ 2same name
- davidanthonyn/claude-skills★ 0same name
- pablopetr/claude-skills★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository53 other files it gives its agents.
- instructions/AGENTS.mdAGENTS.md
- skills/software-development/php-best-practices/AGENTS.mdAGENTS.md
- instructions/CLAUDE.mdCLAUDE.md
- architecture-designerSkill
- caveman-commitSkill
- caveman-compressSkill
- cavemanSkill
- conventional-commitSkill
- youtube-contentSkill
- agentkit-skill-authoringSkill
- skill-orchestrationSkill
- analogical-thinkingSkill
- investigateSkill
- ponytailSkill
- systematic-debuggingSkill
- mermaid-diagramsSkill
- feature-forgeSkill
- find-skillsSkill
- impeccableSkill
- javascript-proSkill
- legacy-modernizerSkill
- migrationSkill
- no-ai-slopSkill
- olakunlevpn-filament-skillsSkill
- clickupSkill
- clickup-tweak-workflowSkill
- git-advancedSkill
- local-wikiSkill
- mr-reviewSkill
- php-proSkill
- doxSkill
- improveSkill
- openspecSkill
- scrutinizeSkill
- systems-thinkingSkill
- tweakSkill
- tweak-workflowSkill
- prompt-engineerSkill
- pest-testingSkill
- php-best-practicesSkill
- security-audit-lightSkill
- security-best-practicesSkill
- spatie-javascriptSkill
- spatie-laravel-phpSkill
- spatie-securitySkill
- spatie-version-controlSkill
- tailwindcss-developmentSkill
- test-driven-developmentSkill
- sql-proSkill
- typescript-proSkill
- ui-ux-pro-maxSkill
- vue-expert-jsSkill
- vue-expertSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
19 rules. 2 are common, 10 are distinctive, and 7 are very specific to this project.
2
Common
Most of the 33 edited versions we read keep these.
10
Distinctive
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Common: line 15
Before applying any rule, check what the application already does.
- Common: line 17
Check sibling files, related controllers, models, or tests for established patterns.
- Distinctive: line 30
Never query in Blade templates
- Distinctive: line 46
No raw SQL with user input — use Eloquent or query builder
- Very specific: line 49
Never commit .env, use config() for secrets, encrypted cast for sensitive DB fields
- Very specific: line 70
Never hardcode table names — use (new Model)->getTable() or Eloquent queries
- Very specific: line 91
Use fakes (Event::fake(), Exceptions::fake(), etc.) — but always after factory setup, not before
- Very specific: line 98
Always implement failed().
- Very specific: line 114
Check response status or use throw()
- Distinctive: line 149
Prefer official Laravel packages and follow conventions, don't override defaults
- Very specific: line 150
Default to ORDER BY id DESC or created_at DESC.
- Distinctive: line 157
Never modify migrations that have run in production
- Distinctive: line 158
Add indexes in the migration, not as an afterthought
- Distinctive: line 179
Follow Laravel naming conventions for all entities
- Very specific: line 180
Prefer Laravel helpers (Str, Arr, Number, Uri, Str::of(), $request->string()) over raw PHP functions
- Distinctive: line 181
No JS/CSS in Blade, no HTML in PHP classes
- Distinctive: line 186
Read relevant rule files before applying advice.
- Distinctive: line 189
Check sibling files for existing patterns — follow those first per Consistency First
- Distinctive: line 190
Verify API syntax against the installed Laravel version and available project documentation
“Common” is measured: kept by at least 6 in 10 of the 33 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Laravel Best Practices
Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. Verify exact API syntax against the installed Laravel version and available project documentation.
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 countcursor()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 WHENinselectRaw) over multiple count queries setRelation()to prevent circular N+1 querieswhereIn+pluck()overwhereHasfor better index usage- Two simple queries can beat one complex query
- Compound indexes matching
orderBycolumn order - Correlated subqueries in
orderByfor has-many sorting (avoid joins)
3. Security → rules/security.md
- Define
$fillableor$guardedon every model, authorize every action via policies or gates - No raw SQL with user input — use Eloquent or query builder
{{ }}for output escaping,@csrfon all POST/PUT/DELETE forms,throttleon auth and API routes- Validate MIME type, extension, and size for file uploads
- Never commit
.env, useconfig()for secrets,encryptedcast for sensitive DB fields
4. Caching → rules/caching.md
Cache::remember()over manual get/putCache::flexible()for stale-while-revalidate on high-traffic dataCache::memo()to avoid redundant cache hits within a request- Cache tags to invalidate related groups
Cache::add()for atomic conditional writesonce()to memoize per-request or per-object lifetimeCache::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 validationafter()instead ofwithValidator()
7. Configuration → rules/config.md
env()only inside config filesApp::environment()orapp()->isProduction()- Config, lang files, and constants over hardcoded text
8. Testing Patterns → rules/testing.md
LazilyRefreshDatabaseoverRefreshDatabasefor speedassertModelExists()over rawassertDatabaseHas()- 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_aftermust exceed jobtimeout; use exponential backoff[1, 5, 10]ShouldBeUniqueto prevent duplicates;ShouldBeUniqueUntilProcessingfor early lock release- Always implement
failed(); withretryUntil(), set$tries = 0 RateLimitedmiddleware 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()orapiResource()- Methods under 10 lines — extract to actions/services
- Type-hint Form Requests for auto-validation
11. HTTP Client → rules/http-client.md
- Explicit
timeoutandconnectTimeouton every request retry()with exponential backoff for external APIs- Check response status or use
throw() Http::pool()for concurrent independent requestsHttp::fake()andpreventStrayRequests()in tests
12. Events, Notifications & Mail → rules/events-notifications.md, rules/mail.md
- Event discovery over manual registration;
event:cachein production ShouldDispatchAfterCommit/afterCommit()inside transactions- Queue notifications and mailables with
ShouldQueue - On-demand notifications for non-user recipients
HasLocalePreferenceon notifiable modelsassertQueued()notassertSent()for queued mailables- Markdown mailables for transactional emails
13. Error Handling → rules/error-handling.md
report()/render()on exception classes or inbootstrap/app.php— follow existing patternShouldntReportfor 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 tasksonOneServer()on multi-server deploymentsrunInBackground()for concurrent long tasksenvironments()to restrict to appropriate environmentstakeUntilTimeout()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 DESCorcreated_at DESC;mb_*for UTF-8 safety defer()for post-response work;Contextfor 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 needslazyById()when updating records while iteratingtoQuery()for bulk operations on collections
18. Blade & Views → rules/blade-views.md
$attributes->merge()in component templates- Blade components over
@include;@pushOncefor per-component scripts - View Composers for shared view data
@awarefor 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
Read relevant rule files before applying advice.
- 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 against the installed Laravel version and available project documentation
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

