MCPInstall

laravel-middleware-patterns

Best practices for Laravel middleware including before/after patterns, terminable middleware, groups, parameters, and common middleware implementations.

Installs
88
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-middleware-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads laravel-middleware-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Middleware Patterns

Creating Middleware

php artisan make:middleware EnsureUserIsSubscribed
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserIsSubscribed
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->user()?->subscribed()) {
            return redirect('billing');
        }

        return $next($request);
    }
}

Before vs After vs Terminable Patterns

Before Middleware

// ✅ Runs before the request hits the controller
class CheckAge
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->age < 18) {
            abort(403, 'Underage access denied.');
        }

        return $next($request);
    }
}

After Middleware

// ✅ Runs after the response is generated
class AddSecurityHeaders
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        $response->headers->set('X-Content-Type-Options', 'nosniff');
        $response->headers->set('X-Frame-Options', 'DENY');
        $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');

        return $response;
    }
}

Terminable Middleware

// ✅ Runs after the response has been sent to the browser
class LogRequest
{
    public function handle(Request $request, Closure $next): Response
    {
        $request->attributes->set('start_time', microtime(true));

        return $next($request);
    }

    public function terminate(Request $request, Response $response): void
    {
        $duration = microtime(true) - $request->attributes->get('start_time');

        Log::info('Request completed', [
            'url' => $request->fullUrl(),
            'method' => $request->method(),
            'status' => $response->getStatusCode(),
            'duration_ms' => round($duration * 1000, 2),
        ]);
    }
}

Registering Middleware in bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {

        // Global middleware (runs on every request)
        $middleware->append(App\Http\Middleware\AddSecurityHeaders::class);
        $middleware->prepend(App\Http\Middleware\TrustProxies::class);

        // Middleware aliases
        $middleware->alias([
            'subscribed' => App\Http\Middleware\EnsureUserIsSubscribed::class,
            'role' => App\Http\Middleware\EnsureUserHasRole::class,
            'locale' => App\Http\Middleware\SetLocale::class,
            'tenant' => App\Http\Middleware\ResolveTenant::class,
        ]);

        // Append to existing groups
        $middleware->appendToGroup('web', [
            App\Http\Middleware\SetLocale::class,
        ]);

        // Define custom groups
        $middleware->group('admin', [
            'auth',
            'role:admin',
            App\Http\Middleware\LogAdminActions::class,
        ]);

        // Middleware priority (execution order)
        $middleware->priority([
            App\Http\Middleware\ResolveTenant::class,
            \Illuminate\Auth\Middleware\Authenticate::class,
            App\Http\Middleware\EnsureUserHasRole::class,
        ]);
    })
    ->create();

Middleware Parameters

class EnsureUserHasRole
{
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        if (! $request->user()?->hasAnyRole($roles)) {
            abort(403, 'Insufficient permissions.');
        }

        return $next($request);
    }
}

Using Middleware Parameters in Routes

// Single parameter
Route::get('/admin', AdminController::class)
    ->middleware('role:admin');

// Multiple parameters
Route::get('/dashboard', DashboardController::class)
    ->middleware('role:admin,editor');

// ✅ Using class reference with parameters
Route::get('/dashboard', DashboardController::class)
    ->middleware(EnsureUserHasRole::class.':admin,editor');

Middleware Groups

// ✅ Apply group to routes
Route::middleware('admin')->group(function () {
    Route::get('/admin/dashboard', [AdminController::class, 'dashboard']);
    Route::get('/admin/users', [AdminController::class, 'users']);
});

// ✅ Multiple middleware
Route::middleware(['auth', 'subscribed', 'role:premium'])->group(function () {
    Route::get('/premium/content', PremiumContentController::class);
});

Excluding Middleware

// ✅ Exclude middleware on a specific route
Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'show']);
    Route::get('/public-page', PublicPageController::class)
        ->withoutMiddleware('auth');
});

// ✅ Exclude from controller
class PublicController extends Controller
{
    public static function middleware(): array
    {
        return [
            new \Illuminate\Routing\Controllers\Middleware('auth', except: ['index', 'show']),
        ];
    }
}

Controller Middleware

use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class PostController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            'auth',
            new Middleware('subscribed', only: ['create', 'store']),
            new Middleware('role:editor', except: ['index', 'show']),
        ];
    }
}

Common Middleware Patterns

Rate Limiting

// bootstrap/app.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

->withMiddleware(function (Middleware $middleware) {
    // Rate limiter is configured in AppServiceProvider
})

// AppServiceProvider
public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });

    RateLimiter::for('uploads', function (Request $request) {
        return Limit::perMinute(5)->by($request->user()->id);
    });
}
// Usage in routes
Route::middleware('throttle:api')->group(function () {
    Route::apiResource('posts', PostController::class);
});

Route::post('/upload', UploadController::class)
    ->middleware('throttle:uploads');

Locale Middleware

class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        $locale = $request->header('Accept-Language')
            ?? $request->user()?->preferred_locale
            ?? config('app.locale');

        if (in_array($locale, config('app.supported_locales', ['en']))) {
            app()->setLocale($locale);
        }

        return $next($request);
    }
}

Tenant Scoping

class ResolveTenant
{
    public function handle(Request $request, Closure $next): Response
    {
        $tenant = Tenant::where('domain', $request->getHost())->first();

        if (! $tenant) {
            abort(404, 'Tenant not found.');
        }

        app()->instance(Tenant::class, $tenant);

        // Set tenant context for queries
        config(['database.connections.tenant.database' => $tenant->database]);

        return $next($request);
    }

    public function terminate(Request $request, Response $response): void
    {
        // Clean up tenant context
        app()->forgetInstance(Tenant::class);
    }
}

CORS Middleware

class HandleCors
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->isMethod('OPTIONS')) {
            $response = response('', 204);
        } else {
            $response = $next($request);
        }

        $response->headers->set('Access-Control-Allow-Origin', config('cors.allowed_origins', '*'));
        $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        $response->headers->set('Access-Control-Max-Age', '86400');

        return $response;
    }
}

Cache Response Middleware

class CacheResponse
{
    public function handle(Request $request, Closure $next, int $minutes = 60): Response
    {
        if ($request->method() !== 'GET') {
            return $next($request);
        }

        $key = 'response_' . sha1($request->fullUrl());

        return Cache::remember($key, now()->addMinutes($minutes), function () use ($next, $request) {
            return $next($request);
        });
    }
}
// Usage
Route::get('/static-page', StaticPageController::class)
    ->middleware(CacheResponse::class.':30');

Best Practices

// ✅ Keep middleware focused on a single responsibility
class EnsureEmailIsVerified { /* only checks email verification */ }
class EnsureUserIsSubscribed { /* only checks subscription */ }

// ❌ Don't combine unrelated concerns in one middleware
class CheckEverything { /* checks auth + subscription + role + locale */ }

// ✅ Use class references instead of string aliases for type safety
Route::middleware(EnsureUserHasRole::class.':admin')->group(function () {
    // ...
});

// ✅ Return early to avoid deep nesting
public function handle(Request $request, Closure $next): Response
{
    if (! $request->user()) {
        return redirect('login');
    }

    return $next($request);
}

// ❌ Avoid modifying the request object extensively
// Use form requests or controller logic for complex input manipulation

Checklist

  • Middleware has a single, clear responsibility
  • Before/after/terminable pattern chosen correctly for the use case
  • Middleware registered in bootstrap/app.php
  • Aliases defined for frequently used middleware
  • Middleware parameters used for configurable behavior
  • Groups created for commonly combined middleware
  • withoutMiddleware() used for route-level exclusions
  • Rate limiting configured for API and sensitive endpoints
  • Controller middleware uses HasMiddleware interface
  • Terminable middleware used for post-response tasks (logging, cleanup)
  • Middleware priority set for execution order dependencies

FAQ

What does the laravel-middleware-patterns skill do?

Best practices for Laravel middleware including before/after patterns, terminable middleware, groups, parameters, and common middleware implementations.

How do I install laravel-middleware-patterns?

Run npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-middleware-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/laravel-middleware-patterns/ (personal) or .claude/skills/laravel-middleware-patterns/ (project).

Which AI agents can use laravel-middleware-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is laravel-middleware-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains laravel-middleware-patterns?

It is published by iserter in iserter/laravel-claude-agents. It has 88 recorded installs.

More from iserter/laravel-claude-agents

View all →

eloquent-best-practices

iserter/laravel-claude-agents

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

laravel-tdd

iserter/laravel-claude-agents

Open the skill to read its SKILL.md instructions.

Backend & APIs378 installs

laravel-blade-component-patterns

iserter/laravel-claude-agents

Open the skill to read its SKILL.md instructions.

Backend & APIs116 installs

api-resource-patterns

iserter/laravel-claude-agents

Open the skill to read its SKILL.md instructions.

Backend & APIs110 installs

laravel-systematic-debugging

iserter/laravel-claude-agents

Systematic debugging process for Laravel applications - ensures root cause investigation before attempting fixes. Use for any Laravel issue (test failures, bugs, unexpected behavior, performance problems).

Backend & APIs102 installs

laravel-validation-patterns

iserter/laravel-claude-agents

Best practices for Laravel validation including Form Requests, custom rules, conditional validation, and input sanitization.

Backend & APIs100 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs