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
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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
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([...]) changes ordering if session or auth middleware must run first.auth, guest, verified, throttle, can, signed.Kernel.php, it still works, but new projects use the slim structure.$middleware->web(...)/api(...) helpers take append and prepend arrays; do not call them with a single class string.