DEV3 Technologies home

DEV3 Developer Forum

Where do I register middleware in Laravel 12 (no Kernel.php)?

Laravel helpSolved0 views
dev3 ·

I followed a tutorial that says add my middleware to app/Http/Kernel.php, but there is no Kernel.php in my Laravel 12 project. How do I register global, group and route middleware now?

#laravel#middleware#laravel-12

0

1 reply

dev3 · Accepted answer

Since Laravel 11 (and in 12) the HTTP kernel is gone. Middleware is configured in bootstrap/app.php through the withMiddleware callback.

use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // global, runs on every request
        $middleware->append(\App\Http\Middleware\TrackVisits::class);

        // add to the web or api group
        $middleware->web(append: [\App\Http\Middleware\SetLocale::class]);
        $middleware->api(prepend: [\App\Http\Middleware\ForceJson::class]);

        // alias for route use
        $middleware->alias([
            'admin' => \App\Http\Middleware\EnsureAdmin::class,
        ]);

        // exclusions and proxies
        $middleware->validateCsrfTokens(except: ['webhooks/*']);
        $middleware->trustProxies(at: '*');
    })
    ->withExceptions(function ($exceptions) {})
    ->create();

Use the alias on routes:

Route::middleware(['auth', 'admin'])->group(function () { /* ... */ });

Create a class

php artisan make:middleware EnsureAdmin

Pitfalls

  • Middleware priority matters. $middleware->priority([...]) changes ordering if session or auth middleware must run first.
  • Class-based aliases for built-ins already exist: auth, guest, verified, throttle, can, signed.
  • If an upgraded app still has a Kernel.php, it still works, but new projects use the slim structure.
  • The $middleware->web(...)/api(...) helpers take append and prepend arrays; do not call them with a single class string.
0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.