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

laravel-agent-rules / routes

CLAUDE.md9 starsChanged 15 days agoMITView on GitHub

Fresh Laravel 12/13 applications ship web.php and console.php. Add API routing with php artisan install:api and broadcasting with php artisan install:broadcasting when needed; inspect their generated bootstrap/app.php wiring. Admin + API combo:

The file

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

9 rules. About 0 are common, 1 is distinctive, and 8 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.

  • 8

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    MUST NOT: put business logic in route files.

    line 21
  2. Very specific:

    MUST: keep URL segments lowercase.

    line 22
  3. Very specific:

    SHOULD: prefer resource routes for CRUD: Route::resource('users', UserController::class).

    line 25
  4. Very specific:

    SHOULD: use route-model binding (/users/{user}) over manual lookups.

    line 26
  5. Very specific:

    MUST: use Route::scopeBindings() (or ->scopeBindings() on a group) for nested routes — enforces the parent-child relationship.

    line 27
  6. Very specific:

    SHOULD: keep per-version route files under routes/api/v{N}.php rather than one giant routes/api.php.

    line 103
  7. Very specific:

    MUST: call ->withoutOverlapping() on any task whose runtime may exceed its interval.

    line 137
  8. Very specific:

    MUST: call ->onOneServer() in multi-server deployments.

    line 138
  9. Very specific:

    SHOULD: call ->description('...') on closure schedules so php artisan schedule:list is readable.

    line 142

≈ “Common” is an estimate: at least 1 in 5 of the 29,248 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

Routing

Route files

  • web — browser HTTP, session/cookies, CSRF
  • api — stateless HTTP, token auth
  • channels — broadcasting (WebSockets)
  • console — Artisan command routes

Fresh Laravel 12/13 applications ship web.php and console.php. Add API routing with php artisan install:api and broadcasting with php artisan install:broadcasting when needed; inspect their generated bootstrap/app.php wiring.

Naming

EntityPatternExamples
Route URLlowercase; plural for resource collections/users, /products; singular OK for auth/self (/login, /me)
Route namesnake_case with dot notationusers.show, products.index, categories.create

Rules

  • MUST NOT put business logic in route files. A route maps a URL to a controller, invokable, or single-action class — AVOID closures that contain logic beyond a one-line delegation. Laravel 12/13 can serialize closure routes for route caching; controller delegation is a separation-of-concerns choice.
  • MUST keep URL segments lowercase. MUST use plural segments for resource collections (/users, /orders/{order}); singular or non-resource paths are fine for auth, settings, and one-off actions (/login, /me, /settings).
  • MUST give every route a name; use dot notation.
  • MUST group routes by entity, then nest middleware/prefix groups outside the entity group.
  • SHOULD prefer resource routes for CRUD: Route::resource('users', UserController::class).
  • SHOULD use route-model binding (/users/{user}) over manual lookups.
  • MUST use Route::scopeBindings() (or ->scopeBindings() on a group) for nested routes — enforces the parent-child relationship. Separately scope and authorize the parent against the authenticated tenant/owner; scoped child binding does not provide tenant authorization.
  • MUST put tenant scoping for route-model binding on the model: a tenant global scope (#[ScopedBy], see app/Models/CLAUDE.md) or a trait that overrides resolveRouteBindingQuery(). Every route that binds the model is then scoped, whatever its placeholder is called. A Route::bind('reservation', ...) covers only the {reservation} placeholder; a later route that uses {booking} for the same model binds across tenants.
  • MUST match the route placeholder to the type-hinted argument name ({conversation} with Conversation $conversation). A mismatch skips implicit binding and can inject a fresh, unpersisted model through the container rather than the requested row; optional arguments may resolve to null.
  • MUST constrain free-form route parameters at the route boundary. Prefer typed helpers (whereNumber(), whereUuid(), whereAlpha(), whereAlphaNumeric(), whereIn()) over regex when they express the rule; invalid values should 404 before the controller runs.
  • Route::redirect() and Route::permanentRedirect() drop the query string: the destination is built from route parameters only, so campaign and attribution parameters are lost. Where the old URL can arrive with a query, MUST forward it: Route::get('/old', fn (Request $request) => redirect()->route('new', $request->query(), 301));.

Example

Route::middleware('auth')->prefix('users')->name('users.')->group(function () {
    Route::get('/', UserIndex::class)->name('index');
    Route::get('/{user}', UserShow::class)->name('show');
});

Admin + API combo:

Route::prefix('/admin')
    ->name('admin.')
    ->middleware(HandleLocale::class)
    ->group(function () {
        Route::resource('users', UserController::class);
        Route::resource('orders', OrderController::class);
    });

Parameter constraints

Route::get('/users/{user}', [UserController::class, 'show'])
    ->whereNumber('user')
    ->name('users.show');

Route::get('/docs/{locale}/{page}', [DocumentationController::class, 'show'])
    ->whereIn('locale', ['en', 'es', 'de'])
    ->whereAlphaNumeric('page')
    ->name('docs.show');

Scoped nested routes

Route::middleware('auth:sanctum')->prefix('conversations')->group(function () {
    Route::post('/', [ConversationController::class, 'store'])->name('conversations.store');

    Route::scopeBindings()->group(function () {
        Route::get('/{conversation}', [ConversationController::class, 'show'])
            ->name('conversations.show');

        Route::post('/{conversation}/messages', [MessageController::class, 'store'])
            ->name('conversation-messages.store');

        Route::get('/{conversation}/messages/{message}', [MessageController::class, 'show'])
            ->name('conversation-messages.show');
    });
});

API versioning

Version public APIs via a prefix + name group. Per-version controllers live under App\Http\Controllers\Api\V{N}\ and are referenced by FQCN (or imported class) in the route file — AVOID string ->namespace(...) groups.

use App\Http\Controllers\Api\V1\InvoiceController;

Route::prefix('v1')
    ->name('v1.')
    ->middleware(['api', 'auth:sanctum', 'throttle:60,1'])
    ->group(function () {
        Route::apiResource('invoices', InvoiceController::class);
        // or: require base_path('routes/api/v1.php');
    });
  • MUST version any externally-consumed API. Breaking changes ship as v2, never as silent edits to v1.
  • SHOULD keep per-version route files under routes/api/v{N}.php rather than one giant routes/api.php.

Rate limiting

  • MUST apply throttle:{max},{minutes} middleware (or a named limiter) to every public, unauthenticated, or expensive endpoint.
Route::middleware('throttle:5,1')->post('/login', LoginController::class);

For complex/named limiters, define them in App\Providers\AppServiceProvider::boot() with RateLimiter::for(...) and reference by name (throttle:uploads). There is no RouteServiceProvider — see app/Http/Middleware/CLAUDE.md for the RateLimiter::for() example.

Custom parameter → model binding

To resolve {conversation} to a class with a different name, register an explicit binding:

Route::model('conversation', AiConversation::class);

For non-trivial resolution logic, override resolveRouteBindingQuery() or resolveRouteBinding() on the model, so the logic follows the model to every route. Route::bind() applies to one placeholder name only; keep it for placeholder-specific resolution, never for tenant or ownership scoping.

Task scheduling (routes/console.php)

Scheduled tasks live in routes/console.php using the Schedule facade — NOT in app/Console/Kernel.php (removed from the modern skeleton).

use Illuminate\Support\Facades\Schedule;

Schedule::command('telescope:prune')->daily();
Schedule::command('app:fetch-users')->everyFiveMinutes();
Schedule::call(fn () => Account::recompute())->hourly()->description('Recompute account balances');
  • MUST call ->withoutOverlapping() on any task whose runtime may exceed its interval. Default lock holds 24h — pass expiresAt: $minutes to recover faster after a crashed worker.
  • MUST call ->onOneServer() in multi-server deployments. Requires a redis, memcached, or database cache driver.
  • SHOULD chain monitoring hooks: ->before(fn), ->after(fn), ->onSuccess(fn), ->onFailure(fn).
  • SHOULD integrate with a healthcheck service via ->pingOnSuccess('https://...') / ->pingOnFailure('https://...').
  • SHOULD scope env-specific tasks with ->environments(['production']).
  • SHOULD call ->description('...') on closure schedules so php artisan schedule:list is readable.
  • SHOULD pin a ->timezone('America/New_York') on time-sensitive tasks; defaults to the app timezone.
  • ->evenInMaintenanceMode() — for must-run-always tasks (billing, queue health pings).

Sub-minute frequencies: everySecond(), everyTwoSeconds(), everyFiveSeconds(), everyTenSeconds(), everyThirtySeconds().

In production, invoke php artisan schedule:run every minute via cron (or an equivalent scheduler service). With sub-minute events, Laravel keeps that invocation alive until the minute ends and repeats the due events; schedule:work is convenient locally. Dispatch queued jobs or background commands for slow sub-minute work, and run schedule:interrupt after deployment to stop an old invocation from continuing with old code.

Dry-run a single task:

php artisan schedule:test

Middleware rules live in app/Http/Middleware/CLAUDE.md.

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.