Laravel Best Practices
LaravelOfficialCreated by laravel
- Skill
- Guidelines
- Software development
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
Laravel best practices provides a structured set of guidelines for writing, reviewing, and refactoring Laravel applications. It emphasizes maintaining consistency with existing codebase patterns while offering standardized approaches for common concerns such as database performance, Eloquent usage, security, validation, and architectural design. The skill acts as a reference index, directing developers to specific rule files based on the task at hand.
What it does
- Provides a categorized index of rules for various Laravel components.
- Promotes consistency by prioritizing existing project patterns over new abstractions.
- Offers guidance on database performance, including eager loading and query optimization.
- Covers security, validation, routing, and error handling patterns.
- Advises on architectural decisions, service classes, and job management.
- Encourages the use of native framework features over custom helpers.
When to use it
- When writing new controllers, models, or service classes in Laravel.
- During code reviews to ensure alignment with established framework patterns.
- When refactoring existing code to improve maintainability or security.
- When addressing specific issues like N+1 queries or complex Eloquent relationships.
- When making architectural decisions regarding application structure.
Advantages
- Ensures architectural consistency across the codebase.
- Reduces technical debt by discouraging speculative abstractions.
- Provides clear, domain-specific guidance for common Laravel tasks.
- Helps prevent common pitfalls like hidden N+1 queries and security vulnerabilities.
Usage examples
- “How should I structure my Eloquent queries to avoid N+1 issues?”
- The agent will reference the database performance and Eloquent rule files to suggest eager loading strategies and proper relationship definitions.
- “Review this controller for security and validation best practices.”
- The agent will evaluate the code against the security and validation rule files, suggesting improvements for input handling and authorization.
- “Should I create a new helper function for this logic?”
- The agent will advise on whether to use existing framework features or if the logic warrants a new service class based on architectural guidelines.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/laravel/laravel-best-practices/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip laravel-best-practices.zip -d .agents/skills
Documentation by laravel
Laravel best practices
Best practices for Laravel, organized as an index of rule files. Each rule file 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 several valid approaches. The best choice is the one the codebase already uses, even if another pattern would be better in theory. Inconsistency is worse than a suboptimal pattern.
Check sibling files and 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.
How to apply
Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.
Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.
Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.
Verify version-sensitive Laravel APIs for the installed version with
search-docs, or inspect the installed framework whensearch-docsis unavailable.Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.
Re-read the diff against every mapped rule before finishing.
Rule index
Cross-cutting changes often need more than one rule file.
| Concern | Read |
|---|---|
| Query count, eager loading, indexes, large datasets | rules/db-performance.md |
| Subqueries, aggregates, complex ordering and query plans | rules/advanced-queries.md |
| Models, relationships, scopes, casts | rules/eloquent.md |
| Authentication, authorization, input safety, secrets, uploads | rules/security.md |
| Form Requests and validation rules | rules/validation.md |
| Controllers, route binding, resources, middleware | rules/routing.md |
| Schema changes, columns, foreign keys, indexes | rules/migrations.md |
| Jobs, retries, uniqueness, batches, Horizon | rules/queue-jobs.md |
| Cache lifetime, invalidation, locks, memoization | rules/caching.md |
| Outbound requests, retries, timeouts, fakes | rules/http-client.md |
| Exceptions, reporting, rendering, log context | rules/error-handling.md |
| Events and notifications | rules/events-notifications.md |
| Mailables and mail assertions | rules/mail.md |
| Scheduled tasks and overlap protection | rules/scheduling.md |
| Collections, lazy iteration, bulk operations | rules/collections.md |
| Blade components, attributes, composers | rules/blade-views.md |
| Environment values and application configuration | rules/config.md |
| Tests: coverage, factories, fakes, and assertions | the testing-best-practices skill |
| Naming, helpers, file boundaries, PHP style | rules/style.md |
| Actions, services, dependencies, application structure | rules/architecture.md |
Decision rules
Prefer framework features and existing application abstractions over new helpers or dependencies.
Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.
Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization.
Files
- ATTRIBUTION.mdAdded by AutoGineer924 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md4.5 KiB
- rules/advanced-queries.md4.2 KiB
- rules/architecture.md6.3 KiB
- rules/blade-views.md1.8 KiB
- rules/caching.md3.3 KiB
- rules/collections.md2.4 KiB
- rules/config.blade.phpScript2.1 KiB
- rules/db-performance.md5.5 KiB
- rules/eloquent.md3.9 KiB
- rules/error-handling.md3.1 KiB
- rules/events-notifications.blade.phpScript2.6 KiB
- rules/http-client.md4.4 KiB
- rules/mail.blade.phpScript2.0 KiB
- rules/migrations.blade.phpScript3.5 KiB
- rules/queue-jobs.md4.3 KiB
- rules/routing.md3.7 KiB
- rules/scheduling.blade.phpScript2.7 KiB
- rules/security.blade.phpScript5.8 KiB
- rules/style.md4.2 KiB
- rules/validation.md2.9 KiB
rules/security.blade.php
@php
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
@endphp
# Security best practices
## Control mass assignment
Define `$fillable` when a model is populated from request-derived arrays, or deliberately guard attributes by another consistent model convention. Laravel models guard all attributes by default. `$guarded = []` opts out of that protection.
```php
class User extends Model
{
protected $fillable = [
'name',
'email',
'password',
];
}
```
Do not pass untrusted request data to a model with `$guarded = []`. Mass-assignment protection controls which attributes `create()`, `fill()`, and `update()` may set. It does not validate values or authorize the operation.
## Authorize protected actions
Use policies, gates, or form request authorization for actions that depend on the current user's permissions. Authentication alone does not establish permission, and validation is not authorization.
```php
public function update(UpdatePostRequest $request, Post $post): RedirectResponse
{
Gate::authorize('update', $post);
$post->update($request->validated());
return redirect()->route('posts.show', $post);
}
```
Authorization may instead live in the form request:
```php
public function authorize(): bool
{
return $this->user()?->can('update', $this->route('post')) ?? false;
}
```
Public actions intentionally available to everyone do not need a redundant authorization check.
## Bind query parameters
Use Eloquent, the query builder, or explicit bindings instead of interpolating untrusted values into Structured Query Language (SQL). Bindings protect values, not identifiers such as column names or sort directions. Map user-selected identifiers to an allow-list.
Incorrect:
```php
DB::select("SELECT * FROM users WHERE name = '{$request->name}'");
```
Correct:
```php
User::where('name', $request->name)->get();
User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get();
```
## Escape output in its context
Blade's `@{{ }}` syntax HTML-escapes output. Use `@{!! !!}` only for content sanitized for the exact HTML context where it renders. Escaping rules differ for HTML, URLs, JavaScript, and Cascading Style Sheets.
Incorrect for untrusted content:
```blade
@{!! $user->bio !!}
```
Correct:
```blade
@{{ $user->bio }}
```
## Apply cross-site request forgery protection
Include `@@csrf` in state-changing Blade forms handled by Laravel's `web` middleware. Routes intentionally excluded from cross-site request forgery (CSRF) verification, such as validated third-party webhooks, need their own authenticity check.
```blade
<form method="POST" action="/posts">
@@csrf
<input type="text" name="title">
</form>
```
Inertia applications commonly use Axios, which returns the encrypted `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. When you use another HTTP client, confirm equivalent configuration. Do not disable CSRF protection only to fix a token mismatch.
## Rate limit sensitive endpoints
Apply suitable rate limits to login attempts, password recovery, verification messages, and expensive or abuse-prone application programming interface (API) routes. Choose the limiter key deliberately. An Internet Protocol (IP) address alone can unfairly group users behind a shared network. An account identifier alone can enable targeted denial of service.
```php
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by(Str::transliterate(
Str::lower($request->string('email')).'|'.$request->ip()
));
});
Route::post('/login', LoginController::class)->middleware('throttle:login');
```
Rate limiting reduces abuse. It does not replace authentication, authorization, or upstream denial-of-service protection.
## Validate and store uploads safely
Validate the expected content type, the size, and the dimensions where relevant. Laravel's `mimes` rule reads the file contents and guesses a Multipurpose Internet Mail Extensions (MIME) type corresponding to the listed extensions. It does not validate the user-assigned filename extension. The `extensions` rule checks that extension. Do not use it by itself.
```php
public function rules(): array
{
return [
'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
];
}
```
Use Laravel's storage methods to generate a filename, and store untrusted files outside a publicly executable location. Public files can require additional controls, such as image re-encoding, content-disposition headers, and explicit blocking of active formats.
```php
$path = $request->file('avatar')->store('avatars');
```
## Keep secrets out of application code
Do not commit populated environment files or hard-code credentials. Read environment variables in configuration files, then use `config()` in application code so configuration caching works. See the configuration rules for encrypted environment files and external secret stores.
## Audit dependencies
Run `{{ $assist->composerCommand('audit') }}` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly.
```bash
{{ $assist->composerCommand('audit') }}
```
## Encrypt sensitive attributes when appropriate
Use an `encrypted` cast for sensitive values that must be recoverable, and use `$hidden` to omit them from array and JavaScript Object Notation (JSON) serialization. Hidden attributes remain accessible in PHP, and encryption does not replace access control. You cannot meaningfully query encrypted values. Store them in a `TEXT` or larger column because ciphertext length varies.
```php
class Integration extends Model
{
protected $hidden = ['api_key', 'api_secret'];
protected function casts(): array
{
return [
'api_key' => 'encrypted',
'api_secret' => 'encrypted',
];
}
}
```
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- laravel
- Publisher
- Laravel (Official)
- Source
- laravel/boost · .ai/laravel/skill/laravel-best-practices · commit 5f8d05d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by laravel or Laravel.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download laravel-best-practices.zip