In Laravel 11, the middleware configuration and customization has been moved from the `Kernel.php` file to the `bootstrap/app.php` file. The new methods for middleware customization in Laravel 11 are:
1. Registering Middleware:
- You can register middleware to be applied to all routes using the `$middleware->use()` method.
- You can register middleware to be applied only to web routes using the `$middleware->web()` method.
- You can register middleware to be applied only to API routes using the `$middleware->api()` method.
Example:
php
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
// Apply middleware to all routes
$middleware->use([ExampleMiddleware::class]);
// Use it only in the web routes
$middleware->web([ExampleMiddleware::class]);
// API only
$middleware->api([ExampleMiddleware::class]);
})
// Other configuration
->create();
2. Disabling Middleware:
- You can disable specific middleware for certain routes using the `$middleware->except()` method.
Example:
php
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
$middleware->validateCsrfTokens(
except: ['stripe/*']
);
})
// Other configuration
->create();
3. Customizing Middleware Behavior:
- You can customize the behavior of the default middleware, such as invalidating sessions on other devices, using the `$middleware` methods.
Example:
php
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
$middleware->authenticateSessions();
})
// Other configuration
->create();
These new methods provide a more centralized and flexible way to manage middleware in Laravel 11 applications, without the need for a separate `Kernel.php` file.
Citations:[1] https://www.itsolutionstuff.com/post/how-to-customize-default-middleware-in-laravel-11example.html
[2] https://scalybee.com/laravel-11-preview-a-glimpse-into-upcoming-changes/
[3] https://stackoverflow.com/questions/78340907/how-do-i-register-a-middleware-in-laravel-11
[4] https://laravel-news.com/laravel-11-directory-structure
[5] https://laravel.com/docs/11.x/releases