Reader Stacks

Creating Custom Middleware in Laravel 11

Laravel 11 removed app/Http/Kernel.php — here is how middleware registration actually works now, with a working example.

Laravel 11 restructured how middleware is registered. If you're following an older tutorial and looking for app/Http/Kernel.php to add your middleware alias, you won't find it — that file no longer exists in a fresh Laravel 11 or 12 install. Registration now happens in bootstrap/app.php.

1. Generate the middleware

php artisan make:middleware EnsureUserIsSubscribed

This creates app/Http/Middleware/EnsureUserIsSubscribed.php:

<?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()->route('billing.index');
        }

        return $next($request);
    }
}

2. Register it in bootstrap/app.php

Open bootstrap/app.php and use the withMiddleware() callback:

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'subscribed' => \App\Http\Middleware\EnsureUserIsSubscribed::class,
    ]);
})

This is the direct replacement for the old $routeMiddleware array in Kernel.php. The same Middleware object also has append(), prepend(), and group() methods for adding middleware to the global stack or to the web/api groups, replacing the old $middlewareGroups array.

3. Use it on a route

Route::get('/dashboard', DashboardController::class)
    ->middleware('subscribed');

Migrating an existing Kernel.php project

If you're upgrading a Laravel 10 project rather than starting fresh, Laravel 11's upgrade path keeps Kernel.php working if you don't run the structural migration — the new bootstrap/app.php style is the default for new applications, not a forced migration for existing ones. Check which pattern your project actually uses before copying either version of this example.

Topics: Authentication & Access Control