Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Customizing laravel 11 kernel
    Laravel CSRF


Customizing laravel 11 kernel


In Laravel 11, the `Kernel.php` file has been removed from the project structure. Instead, middleware configuration is now done through the `bootstrap/app.php` file[1][3][4][5].

To customize middleware in Laravel 11:

1. Open the `bootstrap/app.php` file.

2. Use the `withMiddleware()` method to configure middleware:

php
return Application::configure()
    // ...
    ->withMiddleware(function (Middleware $middleware) {
        // Customize middleware here
    })
    // ...
    ->create();

3. Inside the closure passed to `withMiddleware()`, you can customize middleware using the following methods[2][3]:

- `redirectGuestsTo()`: Customize where guests are redirected
- `redirectTo()`: Customize where users and guests are redirected
- `encryptCookies()`: Exclude cookies from being encrypted
- `validateCsrfTokens()`: Exclude routes from CSRF protection
- `validateSignatures()`: Exclude routes from URL signature validation
- `convertEmptyStringsToNull()`: Prevent converting empty strings in requests
- `trimStrings()`: Prevent string trimming in requests

For example, to exclude some routes from CSRF protection:

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

4. You can also add your own custom middleware by appending it to the `web` middleware group[3]:

php
$middleware->web(append: \App\Http\Middleware\ExampleMiddleware::class);

So in summary, middleware customization in Laravel 11 is now done in `bootstrap/app.php` using the `withMiddleware()` method, rather than in the `Kernel.php` file. This provides a more centralized and streamlined approach to configuring middleware.

Citations:
[1] https://stackoverflow.com/questions/62265811/how-to-move-laravel-kernel-php-file-to-custom-directory
[2] https://benjamincrozat.com/customize-middleware-laravel-11
[3] https://dev.to/grantholle/exploring-middleware-in-laravel-11-2e10
[4] https://www.reddit.com/r/laravel/comments/1beh7p3/migrated_to_laravel_11_10_middleware_kernel_etc/
[5] https://laravel-news.com/laravel-11-directory-structure