Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon What changes were made to middleware configuration in Laravel 11
    Laravel CSRF


What changes were made to middleware configuration in Laravel 11


In Laravel 11, the middleware configuration has been significantly changed compared to previous versions. Here are the key changes:

1. Removal of the HTTP Kernel: The familiar `Kernel.php` file in the `App\Http` directory has been removed. This file previously contained the middleware configuration.

2. Middleware Configuration in `bootstrap/app.php`: The middleware configuration is now handled in the `bootstrap/app.php` file, using the `withMiddleware()` method of the `Application` class.

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();

3. Customizing Middleware Behavior: The `Middleware` class provides methods to customize the behavior of the default middleware, such as disabling CSRF protection on specific routes or invalidating sessions on other devices.

Example:

php
->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(
        except: ['stripe/*']
    );

    $middleware->authenticateSessions();
})

4. Automatic Middleware Registration: With the removal of the HTTP Kernel, middleware is now automatically registered with the Laravel application. You can create a new middleware using the `artisan make:middleware` command, and it will be available for use without any additional registration.

In summary, the key changes to middleware configuration in Laravel 11 are:
- Removal of the HTTP Kernel file
- Middleware configuration moved to the `bootstrap/app.php` file
- Ability to customize middleware behavior using the `Middleware` class
- Automatic registration of middleware, eliminating the need for manual registration

This shift towards a more centralized and customizable middleware configuration aims to simplify the application structure and provide more flexibility in managing middleware in Laravel 11 projects.

Citations:
[1] https://securinglaravel.com/security-tip-laravel-11s-middleware/
[2] https://scalybee.com/laravel-11-preview-a-glimpse-into-upcoming-changes/
[3] https://dev.to/grantholle/exploring-middleware-in-laravel-11-2e10
[4] https://laravel.com/docs/11.x/releases
[5] https://laraveldaily.com/post/laravel-11-main-new-features-changes