Index of every page on this site: llms.txt
All skills
laravel avatar

/laravel-best-practices

@6004f09
by laravellaravel/boost3.7k stars
390
Run it yourself

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.

Use this Skill: https://skilld.dev/gh/laravel/boost/laravel-best-practices

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

ruleseloquent.md

≈1k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Eloquent best practices

Define precise relationship types

Define the relationship that matches the database association, and declare its concrete return type.

public function comments(): HasMany
{
    return $this->hasMany(Comment::class);
}

public function author(): BelongsTo
{
    return $this->belongsTo(User::class, 'user_id');
}

Use local scopes for reusable queries

Extract reusable query constraints into local scopes to avoid duplication.

Duplicated constraints:

$active = User::where('verified', true)->whereNotNull('activated_at')->get();
$articles = Article::whereHas('user', function ($q) {
    $q->where('verified', true)->whereNotNull('activated_at');
})->get();

Reusable local scope:

#[Scope]
protected function active(Builder $query): Builder
{
    return $query->where('verified', true)->whereNotNull('activated_at');
}

// Usage
$active = User::active()->get();
$articles = Article::whereHas('user', fn ($q) => $q->active())->get();

Apply global scopes sparingly

A global scope silently modifies every query on the model, so queries become hard to debug. Prefer local scopes, and reserve global scopes for universal constraints such as soft deletes or multi-tenancy.

Global scope tradeoff:

class PublishedScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $builder->where('published', true);
    }
}

// Admin panels, reports, and jobs now omit drafts unless the scope is removed.

Explicit local scope:

#[Scope]
protected function published(Builder $query): Builder
{
    return $query->where('published', true);
}

Post::published()->paginate(); // Explicit
Post::paginate(); // Admin sees all

Define attribute casts

Use the casts() method for automatic type conversion. If the project convention is the $casts property, follow that convention.

protected function casts(): array
{
    return [
        'is_active' => 'boolean',
        'metadata' => 'array',
        'total' => 'decimal:2',
    ];
}

Cast date and time attributes

Cast a date or timestamp attribute when application code should treat it as a Carbon instance. Eloquent already casts the conventional created_at and updated_at timestamps.

Manual parsing in the template:

{{ Carbon::parse($order->ordered_at)->toDateString() }}

Model cast:

protected function casts(): array
{
    return [
        'ordered_at' => 'datetime',
    ];
}
{{ $order->ordered_at->toDateString() }}
{{ $order->ordered_at->format('m-d') }}

Use whereBelongsTo() for relationship queries

whereBelongsTo() expresses the relationship constraint without naming its foreign key.

Foreign key constraint:

Post::where('user_id', $user->id)->get();

Relationship-aware constraint:

Post::whereBelongsTo($user)->get();
Post::whereBelongsTo($user, 'author')->get();

Keep application queries model-aware

Prefer Eloquent models and relationships for model-backed application queries. They preserve casts, scopes, and model table configuration. The query builder and raw SQL require table names. Use them when you intend their lower-level behavior.

Lower-level alternatives:

DB::table('users')->where('active', true)->get();

$query->join('companies', 'companies.id', '=', 'users.company_id');

DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);

Model-aware queries:

User::where('active', true)->get();
Order::where('status', 'pending')->get();

When a query builder operation should follow a model's configured table name, use (new User)->getTable(). For complex joins or raw SQL, explicit table names may be clearer. When the schema can change, cover those table references with tests.

In migrations, use explicit table names rather than application models. Migrations are historical snapshots, but models and their scopes can change after you deploy a migration.

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts1mo3 checks · Risk SAFE
  • Gen Agent Trust Hub1mo

    The skill provides a comprehensive set of best practices for Laravel development, including specific guidance on security, performance, and architecture. No malicious patterns or security risks were identified.

  • Socket1mo

    No alerts

  • Snyk1mo

    Risk: LOW · No issues

Signed by skilld at 6004f09. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub last week.

Activeupdated last month
metadata
{
  "author": "laravel"
}

README badge

README badge for laravel/boost/laravel-best-practices