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.

rulesstyle.md

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

Convention and style best practices

Follow project naming conventions

Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile.

Element Convention Example
Controller Singular resource name ArticleController
Model Singular StudlyCase User
Table Plural snake_case article_comments
Pivot table Singular model names in alphabetical order, in snake_case article_user
Column snake_case meta_title
Conventional foreign key Singular model name plus _id, in snake_case article_id
Resource URI Plural resource articles/1
Route name Dotted segments, with snake_case within a segment when needed users.show_active
Method camelCase getAll
Variable camelCase $articlesWithAuthor
Collection Descriptive and plural $activeUsers
Object Descriptive and singular $activeUser
View kebab-case show-filtered.blade.php
Configuration file snake_case google_calendar.php
Enumeration Singular StudlyCase UserType

Prefer clear, idiomatic syntax

Use Laravel helpers and query methods when they communicate intent more directly. Do not shorten code when the result is ambiguous or loses useful type information.

More verbose Idiomatic alternative
Session::get('cart') session('cart')
$request->session()->get('cart') session('cart')
return Redirect::back() return back()
Carbon::now() now()
->where('column', '=', 1) ->where('column', 1)
->orderBy('created_at', 'desc') ->latest()
->orderBy('created_at', 'asc') ->oldest()
->first()?->name ->value('name') when only that value is needed

Use typed request accessors such as $request->string(), $request->integer(), and $request->boolean() when their coercion matches the operation.

Use utilities when they clarify intent

Laravel's Str, Arr, Number, and Uri utilities provide expressive operations and framework-consistent behavior. Prefer them when they are clearer or safer than an equivalent PHP operation, not as a replacement for every built-in function.

$slug = Str::slug($title);
$short = Str::limit($text, 100);
$class = class_basename(User::class);
$result = Str::of($input)->trim()->replace('_', '-')->lower();

Use Arr for dot notation and common transformations:

$name = Arr::get($array, 'user.name', 'default');
$public = Arr::only($attributes, ['name', 'email']);

Use Number for localized display formatting, not for values you store or calculate:

Number::format(1000000);
Number::currency(1500, 'USD');
Number::fileSize(1024 * 1024);

Use Uri when a structured API helps you build or transform a uniform resource identifier (URI):

$uri = Uri::of('https://example.com/search')
    ->withQuery(['q' => 'laravel', 'page' => 1]);

Before using newer utility classes or methods, check the documentation for the project's Laravel version.

Keep presentation code maintainable

Prefer the project's asset pipeline, components, and existing conventions for substantial JavaScript and Cascading Style Sheets (CSS). Small page-specific scripts or styles can be reasonable in Blade layouts or stacks. Avoid mixing large behavior and style blocks into templates.

Pass server data with an encoding that fits its context. For example, Blade's Js::from() safely formats data for JavaScript:

<script>
    const article = {{ Js::from($article) }};
</script>

Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping.

Write comments that explain why

Prefer clear names and small units of code over comments that restate an operation. Add concise comments for non-obvious constraints, tradeoffs, workarounds, regular expressions, or external behavior that the code cannot express by itself. Keep comments accurate when behavior changes.

Unhelpful:

// Check whether the query has joins.
if (count((array) $builder->getQuery()->joins) > 0) {
    // ...
}

Clearer:

if ($this->hasJoins()) {
    // ...
}

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