Generated banner for Laravel Best Practices
Generated logo for Laravel Best Practices

Laravel Best Practices

LaravelOfficialCreated by laravel

  • Skill
  • Guidelines
  • Software development
  • MIT
  • Low risk
  • Has scripts

From the author

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.
— the description by laravel

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/laravel/laravel-best-practices/download
  2. Unzip 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

  1. 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.

  2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.

  3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.

  4. Verify version-sensitive Laravel APIs for the installed version with search-docs, or inspect the installed framework when search-docs is unavailable.

  5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.

  6. Re-read the diff against every mapped rule before finishing.

Rule index

Cross-cutting changes often need more than one rule file.

ConcernRead
Query count, eager loading, indexes, large datasetsrules/db-performance.md
Subqueries, aggregates, complex ordering and query plansrules/advanced-queries.md
Models, relationships, scopes, castsrules/eloquent.md
Authentication, authorization, input safety, secrets, uploadsrules/security.md
Form Requests and validation rulesrules/validation.md
Controllers, route binding, resources, middlewarerules/routing.md
Schema changes, columns, foreign keys, indexesrules/migrations.md
Jobs, retries, uniqueness, batches, Horizonrules/queue-jobs.md
Cache lifetime, invalidation, locks, memoizationrules/caching.md
Outbound requests, retries, timeouts, fakesrules/http-client.md
Exceptions, reporting, rendering, log contextrules/error-handling.md
Events and notificationsrules/events-notifications.md
Mailables and mail assertionsrules/mail.md
Scheduled tasks and overlap protectionrules/scheduling.md
Collections, lazy iteration, bulk operationsrules/collections.md
Blade components, attributes, composersrules/blade-views.md
Environment values and application configurationrules/config.md
Tests: coverage, factories, fakes, and assertionsthe testing-best-practices skill
Naming, helpers, file boundaries, PHP stylerules/style.md
Actions, services, dependencies, application structurerules/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

rules/advanced-queries.md

Advanced query best practices

Select single relationship values with subqueries

When you need only one value from a has-many relationship, consider a correlated subquery with addSelect() instead of loading the entire relationship. The subquery selects the value as part of the main query, without an additional relationship query.

public function scopeWithLastLoginAt($query): void
{
    $query->addSelect([
        'last_login_at' => Login::select('created_at')
            ->whereColumn('user_id', 'users.id')
            ->latest()
            ->take(1),
    ])->withCasts(['last_login_at' => 'datetime']);
}

Create dynamic relationships with a subquery foreign key

The same pattern can select a foreign key and expose the selected model through a belongsTo relationship. Eager loading that relationship still runs a separate query, but the pattern avoids loading the full has-many collection.

public function lastLogin(): BelongsTo
{
    return $this->belongsTo(Login::class, 'last_login_id');
}

public function scopeWithLastLogin($query): void
{
    $query->addSelect([
        'last_login_id' => Login::select('id')
            ->whereColumn('user_id', 'users.id')
            ->latest()
            ->take(1),
    ])->with('lastLogin');
}

Use conditional aggregates to combine several counts over the same filtered data set into one query. Use toBase() when you need only scalar values and model hydration adds nothing. Confirm the expression syntax against the application's database engine.

$statuses = Feature::toBase()
    ->selectRaw("count(case when status = 'Requested' then 1 end) as requested")
    ->selectRaw("count(case when status = 'Planned' then 1 end) as planned")
    ->selectRaw("count(case when status = 'Completed' then 1 end) as completed")
    ->first();

Reuse loaded parent models with setRelation()

When a parent and its children are already loaded and code also accesses $child->parent, set the inverse relationship to the existing parent instance. Setting the inverse relationship avoids an extra lazy-loading query for each child.

$feature->load('comments.user');
$feature->comments->each->setRelation('feature', $feature);

Compare whereHas() with an IN subquery

whereHas() typically produces an EXISTS subquery, while whereIn() can express the same filter with an IN subquery. Either form can be faster, depending on the database engine, indexes, cardinality, and query plan. Measure both forms with representative data. Neither subquery loads its result set into PHP memory.

Option using EXISTS:

$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));

Option using IN:

$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));

Measure two simple queries against one complex query

Two targeted queries can outperform one complex correlated subquery or join when the first query is highly selective. They also add a database round trip, can transfer a large identifier list, and do not provide a single-query consistency snapshot. Decide from query plans and production-like measurements.

Design composite indexes for the query

For common multi-column sorts, consider a composite index whose column order supports the query's filters and ordering. Database engines may combine indexes or choose an explicit sort, so matching the ORDER BY list alone does not guarantee that the engine uses the index. Verify the query plan.

// Migration
$table->index(['last_name', 'first_name']);

// Query that this index may support
User::query()->orderBy('last_name')->orderBy('first_name')->paginate();

Consider a correlated subquery for has-many ordering

When sorting by one value from a has-many relationship, a direct join can duplicate parent rows unless it first reduces the related table to one row per parent. A correlated subquery in orderBy() is often simpler, but its performance depends on the query plan and supporting indexes.

public function scopeOrderByLastLogin($query): void
{
    $query->orderByDesc(Login::select('created_at')
        ->whereColumn('user_id', 'users.id')
        ->latest()
        ->take(1)
    );
}

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.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download laravel-best-practices.zip