agentleFS
leekleek/laravel-agent-rules/app/CLAUDE.md

laravel-agent-rules / app

CLAUDE.md9 starsChanged 2 months agoMITView on GitHub

Cross-cutting conventions for the whole project. Per-class-type rules live in the matching directory's CLAUDE.md — read both when editing a file. All rules below are MUST unless tagged SHOULD / PREFER / AVOID. Group classes by business domain in a subfolder inside the class-type folder. This adds a domain axis on top of Laravel's default folders — you keep framework conventions and package compatibility while making the business domain obvious. It's the structured alternative to letting a folder fill up…

The file

We split this CLAUDE.md into the rules it gives an agent

7 rules. About 0 are common, 1 is distinctive, and 6 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 6

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    All rules below are MUST unless tagged SHOULD / PREFER / AVOID.

    line 5
  2. Very specific:

    SHOULD: start flat. A class-type folder serving one domain stays flat (app/Models/User.php) — don't pre-create domain folders for a small …

    line 33
  3. Very specific:

    MUST: use one domain name across every folder — Billing/ in Models, Jobs, Policies, and Requests alike.

    line 44
  4. Very specific:

    MUST: keep each method doing one thing.

    line 75
  5. Very specific:

    MUST: use native type hints and return types.

    line 77
  6. Very specific:

    MUST: keep user-facing copy in translation files and read it via __('app.article_added') / trans_choice(...).

    line 108
  7. Very specific:

    MUST: read secrets only via config(...) (never env() outside config/*.php) — see config/CLAUDE.md.

    line 117

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

Laravel Agent Rules

Cross-cutting conventions for the whole project. Per-class-type rules live in the matching directory's CLAUDE.md — read both when editing a file.

All rules below are MUST unless tagged SHOULD / PREFER / AVOID.

Code naming (cross-cutting)

EntityPatternExamples
MethodcamelCasestore, massDestroy, handle
Model propertysnake_caseis_active, created_at
Class propertycamelCase$isActive, $createdAt
VariablecamelCase$isActive, $createdAt
Collection vardescriptive camelCase, plural$activeUsers, $pendingOrders
Object vardescriptive camelCase, singular$activeUser, $pendingOrder

Where does logic go?

SituationUse
Synchronous business operation — the caller needs the resultAction (app/Actions/)
Work that can run later, off the request pathJob (app/Jobs/)
One occurrence, several unrelated side effects (fan-out)Event + Listeners (app/Events/)
Telling a user something via mail / database / SMS / broadcastNotification (app/Notifications/)
Wrapping an external system / SDK, or a cohesive multi-method capabilityService (app/Services/)
Stateless helper with no side effectsSupport class (app/Support/)

Organize by domain (sub-namespacing)

Group classes by business domain in a subfolder inside the class-type folder. This adds a domain axis on top of Laravel's default folders — you keep framework conventions and package compatibility while making the business domain obvious. It's the structured alternative to letting a folder fill up with unrelated classes (or inventing vague catch-alls like Helpers / Utilities, which this repo already replaces with typed homes).

  • SHOULD start flat. A class-type folder serving one domain stays flat (app/Models/User.php) — don't pre-create domain folders for a small app.
  • MUST group by domain subfolder when a folder holds classes from 2+ distinct business domains. Domain count determines this convention, not a file-count threshold; several classes in one domain may remain flat.
  • MUST match the namespace to the directory (PSR-4) and pass the sub-path to make:*:
php artisan make:model   Billing/Invoice            # App\Models\Billing\Invoice
php artisan make:job     Billing/SyncInvoiceToErp
php artisan make:policy  Billing/InvoicePolicy
php artisan make:request Billing/StoreInvoiceRequest
  • MUST use one domain name across every folder — Billing/ in Models, Jobs, Policies, and Requests alike; never Billing in one and Invoicing in another.
  • SHOULD name domains after the app's own vocabulary and keep them aligned with how routes/modules are already grouped.

✅ A grown app grouped by domain — the domain is obvious at a glance:

app/
  Http/Controllers/Billing/InvoiceController.php
  Http/Requests/Billing/StoreInvoiceRequest.php
  Jobs/Billing/SyncInvoiceToErp.php
  Models/Billing/Invoice.php
  Policies/Billing/InvoicePolicy.php

❌ Three domains dumped flat — every folder is a junk drawer:

app/Models/Invoice.php   Order.php   Ticket.php
app/Jobs/SyncInvoiceToErp.php   ShipOrder.php   EscalateTicket.php

Interactions with other folders:

  • Controllers already namespace by audience/version (Api/, Admin/, Api/V{N}/); domain nests inside that axis (Api/V1/Billing/InvoiceController.php) — see app/Http/Controllers/CLAUDE.md.
  • Factories resolve from the model namespace, so a domain-namespaced model looks up Database\Factories\Billing\InvoiceFactory — mirror the subfolder (see database/factories/CLAUDE.md).
  • Migrations are the exception — keep them flat (timestamp-ordered anonymous classes, not PSR-4; migrate ignores subfolders) — see database/migrations/CLAUDE.md.
  • Filament resources are the other exception — group by model, not domain. The layout is app/Filament/Resources/{Models}/; the domain axis there is a Cluster (app/Filament/Clusters/{Domain}/Resources/...), Filament's equivalent of domain sub-namespacing. Reuse the same domain name — Billing/ here → a Billing cluster there. See filament-agent-rules.
  • Tests mirror the source path under app/, preserving class type, audience/version, and domain (tests/Feature/Http/Controllers/Api/V1/Billing/InvoiceControllerTest.php).

Code style (cross-cutting)

  • MUST keep each method doing one thing. Extract a well-named private/protected helper instead of nesting conditionals or growing a method past one screen.
  • PREFER descriptive method and variable names over comments. Write a comment only to explain why (non-obvious intent, an edge case), never what the code already says.
  • MUST use native type hints and return types; AVOID DocBlocks that merely restate them. Use a DocBlock only for types PHP can't express natively (array shapes, iterable-of) — e.g. /** @var OrderItemData[] */.
  • PREFER modern PHP syntax where it improves clarity: constructor property promotion, readonly, enums, match, nullsafe ?->, named arguments, first-class callables. Never sacrifice readability for cleverness.
  • PREFER the shortest readable Laravel syntax: session('cart') over Session::get('cart'); $request->name over $request->input('name'); now()/today(); back(); $model->relation?->id; compact('user'); ->latest()/->oldest(); ->where('active', 1); ->get(['id', 'name']); ->value('name').
  • MUST use community-standard Laravel and first-party tools; AVOID alien replacements. Eloquent (not Doctrine), Blade (not Twig), Policies (not Entrust), Sanctum/Passport for API auth, Migrations for schema, built-in localization, the Task Scheduler, Collections over plain arrays. Don't import patterns from other ecosystems (generic ORMs, repository-per-model, alternate templating/DI) when an idiomatic Laravel approach exists.
  • MUST NOT override or reimplement standard framework features. Extend via the documented seams (service providers, macros, events, contracts) instead of replacing core behaviour.
  • MUST NOT build HTML strings inside PHP classes (controllers, actions, services, mailables, notifications). Render markup in Blade and pass data in. (A Blade render() heredoc in a class-based component is the only sanctioned exception — see app/View/Components/CLAUDE.md.)

Dependency injection (IoC)

  • MUST resolve classes that carry their own dependencies from the container — constructor-inject them, or use app(Foo::class). AVOID new SomeClass(...) for anything with dependencies or an interface binding; hard-wiring concretes couples callers to implementations and blocks testing/mocking. (new is fine for plain value objects / DTOs.)
  • MUST depend on the interface, not the concrete, when one is bound — see app/Providers/CLAUDE.md.

❌ Hard-wired concrete — untestable:

public function handle(array $data): User
{
    $mailer = new MailgunMailer(config('services.mailgun.key'));
    // ...
}

✅ Injected via the container:

public function __construct(private readonly Mailer $mailer) {}

Constants & strings

  • MUST NOT hard-code magic string/number literals for statuses, types, roles, or keys. Use an enum (OrderStatus::Pending — see app/Enums/CLAUDE.md) or a class constant (Article::TYPE_NORMAL).
  • MUST keep user-facing copy in translation files and read it via __('app.article_added') / trans_choice(...). Never inline literal user-facing strings in PHP or Blade. That includes enum/state label() methods, mailable subjects, notification lines, validation messages, and Blade text.
  • Exception — Filament: admin-panel component ->label()s, modal headings, Notification titles, and enum getLabel() follow the Filament ruleset (inline by default; lifted to __() via a global configureUsing default when the panel is localized) — see filament-agent-rules.
  • Exception — developer-only strings: log messages, exception messages for internal failures, and Artisan $description / signatures may stay inline English.

Security (cross-cutting)

  • MUST authorize before acting — policies / Gate::authorize() / route ->can(...) before mutations or sensitive reads. $this->authorize() requires the AuthorizesRequests trait. Never trust a client-supplied id alone for ownership or tenancy.
  • MUST scope lookups to the authenticated boundary (tenant, owner, team) in queries and validation (exists / unique rules) — global scopes and policies do not automatically protect every query.
  • MUST NOT concatenate request input into SQL, shell commands, or raw cache/key fragments. Whitelist sorts, filters, and report dimensions with an enum or explicit map.
  • MUST read secrets only via config(...) (never env() outside config/*.php) — see config/CLAUDE.md.
  • MUST NOT mass-assign unvalidated request data; use Form Requests and $fillable / $guarded deliberately — see app/Http/Requests/CLAUDE.md and app/Models/CLAUDE.md.

Caching

Cache keys, Cache::flexible / locks / memo, tags, null results, and invalidation live in app/Support/CLAUDE.md — apply those rules at every call site (Jobs, Models, Actions), not only under Support classes.

Class shape

  • PREFER final on application classes (Actions, Jobs, DTOs, Support, Services, Policies, etc.) unless the class is intentionally designed for extension (abstract base, package seam, or framework subclass that docs require leaving open).

Class naming index

Per-class-type naming rules are colocated with the directory that holds the class. Quick map:

Class typeDirectory
Actionapp/Actions/
Castapp/Casts/
Channelapp/Broadcasting/
Commandapp/Console/Commands/
Concern (Trait)app/Concerns/
Contract (Interface)app/Contracts/
Controllerapp/Http/Controllers/
Data (DTO)app/Data/
Enumapp/Enums/
Eventapp/Events/
Exceptionapp/Exceptions/
Factorydatabase/factories/
Feature (Pennant)app/Features/
Jobapp/Jobs/
Listenerapp/Listeners/
Livewireapp/Livewire/
Mailapp/Mail/
Middlewareapp/Http/Middleware/
Migrationdatabase/migrations/
Modelapp/Models/
Notificationapp/Notifications/
Observerapp/Observers/
Policyapp/Policies/
Providerapp/Providers/
Requestapp/Http/Requests/
Resource (API)app/Http/Resources/
Ruleapp/Rules/
Scopeapp/Models/Scopes/
Eloquent builderapp/Models/Builders/
Query objectapp/Queries/
Seederdatabase/seeders/
Serviceapp/Services/
Stateapp/States/
Supportapp/Support/
Testtests/
View Componentapp/View/Components/

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.