laravelroutes-best-practices

Keep routes simple: use routes only to map requests to controllers, and avoid putting business logic, validation, or database operations in route files.

Last repository push
GitHub Stars
157
Forks
3
Issues / PRs
0

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "laravelroutes-best-practices" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-e9a3328c24cafff34b10305ea15d25a507f6f45e438e709f4a71f2727a123c6b. Verify the upstream source and version against https://github.com/jpcaparas/superpowers-laravel before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Keep routes simple: use routes only to map requests to controllers, and avoid putting business logic, validation, or database operations in route files.

0 Downloads

Introduction source: third_party · jpcaparas · 0.0.1 Reference

SkillPi interpretation

Tasks
Keep routes clean and focused on mapping requests to controllers; avoid business logic, validation, or database operations in route files
Audience
Route closures are acceptable only for: Simple static page renders Temporary debugging/testing (remove before committing) Quick prototypes (refactor to controllers before production)
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: laravel:routes-best-practices
description: Keep routes clean and focused on mapping requests to controllers; avoid business logic, validation, or database operations in route files

Routes Best Practices

Keep your route files clean and focused on mapping requests to controllers. Routes should never contain business logic, validation, or database operations.

Anti-Pattern: Business Logic in Routes

// BAD: Business logic directly in routes
Route::post('/order/{order}/cancel', function (Order $order) {
    if ($order->status !== 'pending') {
        return response()->json(['error' => 'Cannot cancel'], 400);
    }

    $order->status = 'cancelled';
    $order->cancelled_at = now();
    $order->save();

    Mail::to($order->user)->send(new OrderCancelled($order));

    return response()->json(['message' => 'Order cancelled']);
});

// BAD: Validation in routes
Route::post('/users', function (Request $request) {
    $validated = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users',
    ]);

    return User::create($validated);
});

Best Practice: Clean Route Definitions

// GOOD: Routes only map to controllers
Route::post('/order/{order}/cancel', [OrderController::class, 'cancel']);
Route::post('/users', [UserController::class, 'store']);

// GOOD: Use route groups for organization
Route::prefix('api/v1')->group(function () {
    Route::apiResource('orders', OrderController::class);
    Route::post('orders/{order}/cancel', [OrderController::class, 'cancel']);
});

// GOOD: Named routes for maintainability
Route::post('/order/{order}/cancel', [OrderController::class, 'cancel'])
    ->name('orders.cancel');

// GOOD: Middleware in routes, logic in controllers
Route::middleware(['auth', 'verified'])->group(function () {
    Route::resource('admin/users', AdminUserController::class);
});

Controller Implementation

// app/Http/Controllers/OrderController.php
class OrderController extends Controller
{
    public function __construct(
        private readonly OrderCancellationService $cancellationService
    ) {}

    public function cancel(CancelOrderRequest $request, Order $order)
    {
        $this->cancellationService->cancel($order);

        return response()->json([
            'message' => 'Order cancelled successfully'
        ]);
    }
}

// app/Http/Requests/CancelOrderRequest.php
class CancelOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('cancel', $this->route('order'));
    }

    public function rules(): array
    {
        return [
            'reason' => 'nullable|string|max:500',
        ];
    }
}

Route File Organization

// routes/web.php - Keep it minimal
Route::get('/', [HomeController::class, 'index']);
Route::get('/about', [PageController::class, 'about']);

require __DIR__ . '/auth.php';
require __DIR__ . '/admin.php';

// routes/admin.php - Separate concerns
Route::prefix('admin')
    ->middleware(['auth', 'admin'])
    ->name('admin.')
    ->group(function () {
        Route::get('/dashboard', [AdminDashboardController::class, 'index'])
            ->name('dashboard');
        Route::resource('users', AdminUserController::class);
    });

// routes/api.php - API routes
Route::prefix('v1')->group(function () {
    Route::apiResource('products', Api\ProductController::class);
    Route::post('products/{product}/reviews', [Api\ReviewController::class, 'store']);
});

Key Principles

  1. Routes are declarations, not implementations

    • Define the HTTP verb, path, and controller method
    • Nothing more
  2. Use route model binding

    // Laravel automatically resolves the Order model
    Route::put('/orders/{order}', [OrderController::class, 'update']);
  3. Group related routes

    Route::controller(OrderController::class)->group(function () {
        Route::get('/orders', 'index');
        Route::get('/orders/{order}', 'show');
        Route::post('/orders', 'store');
    });
  4. Use resource controllers when appropriate

    Route::resource('photos', PhotoController::class)
        ->only(['index', 'show'])
        ->names('gallery.photos');
  5. Leverage route caching in production

    sail artisan route:cache

Common Mistakes to Avoid

  • ❌ Database queries in route closures
  • ❌ Complex conditionals or loops in routes
  • ❌ Direct model manipulation in routes
  • ❌ Sending emails or notifications from routes
  • ❌ File operations in route definitions
  • ❌ API calls to external services in routes
  • ❌ Session or cache manipulation in routes

When to Use Route Closures

Route closures are acceptable only for:

  • Simple static page renders
  • Temporary debugging/testing (remove before committing)
  • Quick prototypes (refactor to controllers before production)
// Acceptable for simple static views
Route::view('/terms', 'legal.terms');
Route::view('/privacy', 'legal.privacy');

// Or simple redirects
Route::redirect('/home', '/dashboard');
Route::permanentRedirect('/old-about', '/about');

Testing Routes

test('order cancellation route requires authentication', function () {
    $order = Order::factory()->create();

    $response = $this->postJson("/orders/{$order->id}/cancel");

    $response->assertUnauthorized();
});

test('route names are properly defined', function () {
    expect(route('orders.cancel', ['order' => 1]))
        ->toBe('http://localhost/orders/1/cancel');
});

Remember: If you're writing more than one line of code in a route definition, it belongs in a controller!

Version history

  1. v0.1.5 GitHub ↗
    Original release notes

    # Laravel Superpowers — Release Notes ## v0.1.5 (2025-11-11) Added five new best practice skills based on recommendations from https://saasykit.com/blog/laravel-best-practices to provide comprehensive coverage of Laravel development patterns. ### Added (Skills) - **Routes Best Practices** (`routes-best-practices`) - Keep routes clean and focused on mapping requests to controllers, avoiding business logic in route files - **Data Chunking for Large Datasets** (`data-chunking-large-datasets`) - Handle large datasets efficiently with `chunk()`, `chunkById()`, `lazy()`, and `cursor()` methods - **Internationalization and Translation** (`internationalization-and-translation`) - Build with i18n in mind from day one using Laravel's translation helpers - **Constants and Configuration** (`constants-and-configuration`) - Replace hardcoded values with constants, enums, and configuration for better maintainability - **Documentation Best Practices** (`documentation-best-practices`) - Write meaningful documentation that explains "why" not "what", focusing on complex business logic ### Notes These additions complement the existing comprehensive skill set by filling gaps identified from the SaaSykit Laravel best practices guide. All new skills include extensive examples, anti-patterns, and real-world use cases.

  2. v0.1.4 GitHub ↗
    Original release notes

    # Laravel Superpowers — Release Notes ## v0.1.4 (2025-11-04) Monorepo-aware SessionStart with multi-app detection, per-app version reporting, and scoped Sail guidance. ### Monorepo Support - Recursively discovers Laravel apps by locating `artisan` anywhere in the repo (ignores heavy/irrelevant folders like `vendor/`, `node_modules/`, `storage/`, VCS/IDE folders). - Supports multiple Laravel apps in a single repository. The hook lists all detected apps with: - Relative path - Laravel version (from `composer.lock` via `jq` when available, with fallback to `composer.json` constraint or a portable parser) - Sail availability, and whether containers appear to be running - Determines the “active” app based on the current working directory; if only one app exists, it becomes active automatically. - Emits Sail guidance and interactive safety for the active app only, to avoid cross-app confusion. ### Testing - Extended `scripts/test_session_start.sh` to cover: - Non-Laravel repo bailout - Single app (no Sail) - Sail present but containers stopped (interactive safety messaging) - Sail present with containers running - Monorepo with two nested apps on different Laravel versions - Monorepo where hook runs inside a nested app (active app semantics) - CI workflow `.github/workflows/test-session-start.yml` continues to run this script; no changes required beyond the added scenarios. ### Notes - If `jq` is unavailable, the hook falls back to a portable parser for version detection; output may show version constraints or `unknown` in minimal setups.

  3. v0.1.3 GitHub ↗
    Original release notes

    # Laravel Superpowers — Release Notes ## v0.1.2 (2025-11-04) Docs sweep across Laravel 11.x and 12.x, with new skills matching the intersection of stable patterns. Also consolidated duplicates and kept commands thin. ### Added (Skills) - Form Requests & Validation (`laravel:form-requests`) - Policies & Authorization (`laravel:policies-and-authorization`) - Eloquent Relationships & Loading (`laravel:eloquent-relationships`) - Transactions & Consistency (`laravel:transactions-and-consistency`) - HTTP Client Resilience (`laravel:http-client-resilience`) - Task Scheduling (`laravel:task-scheduling`) - API Resources & Pagination (`laravel:api-resources-and-pagination`) - Blade Components & Layouts (`laravel:blade-components-and-layouts`) - Filesystem Uploads & URLs (`laravel:filesystem-uploads`) - Rate Limiting & Throttle (`laravel:rate-limiting`) - Exception Handling & Logging (`laravel:exception-handling-and-logging`) Matching command wrappers were added under `commands/` using the existing convention. ### Changed - Unified caching guidance into `laravel:performance-caching` (added tags, locks, invalidation best‑practices). Removed the duplicate cache strategies skill/command. - De‑duplicated Eloquent guidance: relationships skill now references `laravel:performance-eager-loading` for N+1 detection/measurement. ### Removed - Subagents that duplicated skills (Form Request Builder, Policy Planner, Transaction Auditor, API Resource Designer). The repo keeps subagents minimal; the controller cleaner remains. - Redundant Sail prompt skill (covered by runner selection and integration docs). ### Docs - Summary of 11.x/12.x intersection captured within the new skills themselves.

  4. v0.1.2 GitHub ↗
    Original release notes

    # Laravel Superpowers — Release Notes ## v0.1.1 (2025-11-04) Smarter Laravel detection, Sail via binary presence, and safer command guidance. ### Detection & Safety - SessionStart now bails out cleanly for non‑Laravel repos (no output), ensuring the plugin does NOT activate outside Laravel projects. - Sail is detected by executable presence only: `vendor/bin/sail` (or a top‑level `./sail` helper). We no longer parse `composer.json` or rely on `jq` for Sail checks. - Determines whether containers are running via `docker compose ps` / `docker-compose ps` (unchanged). - Injects guidance to prefer Sail commands when Sail is available; clearly maps Sail vs host command pairs (artisan/composer/php/node/db). - Interactive safety: when Sail is available but containers are not running, the assistant must ask whether to start containers (`sail up -d`) or proceed using host tools—no host PHP/Composer/DB/Node commands should run until the user chooses. ### Docs & Screenshots - README now includes screenshots of SessionStart with and without Sail. ### Docs & Skills Cleanup - Replaced hardcoded Sail-only lines with Sail/non‑Sail pairs: - `skills/migrations-and-factories/SKILL.md` - `skills/queues-and-horizon/SKILL.md` - `skills/daily-workflow/SKILL.md` - `skills/quality-checks/SKILL.md` - Ensured quality/static analysis and frontend checks include host equivalents. ### New Skill - [Removed] Previously documented interactive Sail prompt skill. Interactive safety is still enforced by the assistant when Sail is declared but containers are not running. ### Reference - Common Sail commands supported: `sail up|stop|restart|ps`, `sail artisan …`, `sail php …`, `sail composer …`, `sail node|npm|npx|pnpm|pnpx|yarn|bun|bunx …`, `sail mysql|mariadb|psql|mongodb|redis|valkey`, `sail test|phpunit|pest|pint|dusk`.

  5. v0.1.0 GitHub ↗
    Original release notes

    ## v0.1.0 (2025-11-03) First public release of Laravel Superpowers — a Laravel‑focused skills library for Claude Code. It brings proven workflows (TDD, debugging, planning) together with Laravel‑aware guidance that stays platform‑agnostic (works with or without Sail). ### Highlights - Plugin identity and marketplace metadata for the Laravel fork - Renamed plugin to `superpowers-laravel` and pointed metadata to `jpcaparas/superpowers-laravel` - Added local marketplace entry to simplify install during development - Laravel‑aware SessionStart - Startup hook auto‑detects Laravel projects (via `artisan` or `composer.json` with `laravel/framework`) - Injects a concise “Using Superpowers in Laravel Projects” introduction when Laravel is detected - New Laravel skills (all Sail/non‑Sail compatible) - Onboarding & Runner (using‑laravel‑superpowers, runner‑selection) - Development & Testing (tdd‑with‑pest, migrations‑and‑factories) - Quality & Operations (quality‑checks, queues‑and‑horizon) - Architecture & Complexity (ports‑and‑adapters, template‑method‑and‑plugins, complexity‑guardrails) - Optional skills (scaffolding for growing teams) - Nova resource patterns; Horizon dashboards/metrics; E2E Playwright patterns - API surface evolution; Config/Env storage strategy - Key commands (plugin‑namespaced) - `/superpowers-laravel:brainstorm`, `/superpowers-laravel:write-plan`, `/superpowers-laravel:execute-plan` - `/superpowers-laravel:laravel-check`, `/superpowers-laravel:laravel-tdd` - Documentation - Updated README for Laravel‑first usage (now includes repo logo) - Added Related Tools note for Laravel Boost (complementary if installed) - New integration guide: `docs/laravel/INTEGRATION.md` - New installation notes (version‑agnostic): `docs/laravel/INSTALLATION-NOTES.md` ### Files - Hook: `hooks/session-start.sh` (Laravel detection + onboarding) - Skills live under `skills/`; commands under `commands/` - Docs: `docs/laravel/INTEGRATION.md`, `docs/laravel/INSTALLATION-NOTES.md` ### New skills inspired by Clean Coders Guide - Controller cleanup; performance (eager loading, select columns, caching); dependency trimming - Helpers; interfaces + DI; strategy; controller testing ### Commands - Examples provided for core flows and a few advanced skills; run `/help` to see everything available in your environment. ### Maintenance - Moved Laravel skills from `skills/laravel/**` to first‑party `skills/**` - Removed empty directories after consolidation - Cleaned references in README and docs to reflect new locations and command namespace - Added CI validation for skills structure and plugin conventions: `.github/workflows/validate-skills.yml` ### Notes - All skills intentionally include Sail/non‑Sail command pairs to avoid platform lock‑in. - Insights is treated as optional; Pint and static analysis (PHPStan/Psalm) are encouraged as baselines.

Current listing version

0.0.1

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value65/100

Highlights

  • 提供 Laravel 路由最佳实践指南,对开发者有实际指导意义
  • 内容详实,涵盖常见错误和正确做法
Trigger Precision85/100

Highlights

  • description 明确描述了核心功能,触发词覆盖合理
  • 边界清晰,用户能准确理解 Skill 用途
Structure and Standards95/100

Highlights

  • 文档结构完整,包含多个逻辑清晰的章节
  • 提供丰富的代码示例和测试用例,便于理解执行
Execution Reliability80/100

Highlights

  • 内容为最佳实践指南,提供完整的代码示例
  • 包含测试用例,确保实践方案的可验证性
Evidence Verifiability (mean of the first four)81/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • localhost

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.