iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌿

How to Configure Middleware in Laravel 11 and Beyond

に公開

Introduction

The way of writing configurations changed significantly when upgrading from Laravel 10 to 11 and later versions.

While middleware groups and alias settings were handled in app/Http/Kernel.php up to Laravel 10, this has moved to bootstrap/app.php in Laravel 11 and beyond.

In this article, I would like to organize the way of writing these configurations for Laravel 11 and later.

Environment

  • PHP 8.4.5
  • Laravel 12.3.0

Registering Middleware

First, let's look at how to specify middleware that runs for every HTTP request.

Laravel 10

Middleware is specified in the $middleware property of app/Http/Kernel.php.

https://github.com/laravel/laravel/blob/v10.3.3/app/Http/Kernel.php#L16-L24

You can change the execution order or specify custom middleware by modifying the elements of the array in the $middleware property.

    protected $middleware = [
        \\App\\Http\\Middleware\\TrimStrings::class, // Change the order so trim runs first
        \\App\\Http\\Middleware\\TrustProxies::class,
        \\Illuminate\\Http\\Middleware\\HandleCors::class,
        \\App\\Http\\Middleware\\PreventRequestsDuringMaintenance::class,
        \\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize::class,
        \\Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull::class,
        \\App\\Http\\Middleware\\AAA::class, // Add custom middleware
    ];

Laravel 12

Middleware is specified using the withMiddleware method in bootstrap/app.php.

https://github.com/laravel/laravel/blob/v12.0.3/bootstrap/app.php#L13-L15

Initially, no logic is written inside. This is because the Illuminate\Foundation\Configuration\Middleware class, passed as an argument to the closure within the withMiddleware method, has default middleware already defined.

https://github.com/laravel/framework/blob/12.x/src/Illuminate/Foundation/Configuration/Middleware.php#L451-L463

Similar to Laravel 10, when specifying middleware, use the append method to add it to the end or the prepend method to add it to the beginning.

use App\Http\Middleware\AAA;
use App\Http\Middleware\BBB;
// use App\Http\Middleware\CCC;
// use App\Http\Middleware\DDD;
// use App\Http\Middleware\EEE;
// use App\Http\Middleware\FFF;

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(AAA::class);
    $middleware->prepend(BBB::class);

    // You can also specify multiple by using an array
    // $middleware->append([CCC::class, DDD::class]);
    // $middleware->prepend([EEE::class, FFF::class]);
})

Also, you can use the replace method to swap default middleware. Furthermore, to remove default middleware, use the remove method.

use App\Http\Middleware\GGG;
//use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull:
use Illuminate\Foundation\Http\Middleware\TrimStrings;
use Illuminate\Http\Middleware\ValidatePostSize;

->withMiddleware(function (Middleware $middleware) {
    $middleware->replace(TrimStrings::class, GGG::class);

    $middleware->remove(ValidatePostSize::class);

    // The remove method also accepts an array for multiple specifications
    // $middleware->remove([TrimStrings::class, ConvertEmptyStringsToNull::class]);
})

While you can rewrite specifications using each method, you can also use the use method to rewrite them all at once.

->withMiddleware(function (Middleware $middleware) {
    $middleware->use([
        \App\Http\Middleware\HHH::class,
        \Illuminate\Http\Middleware\ValidatePathEncoding::class,
        \Illuminate\Foundation\Http\Middleware\InvokeDeferredCallbacks::class,
        \Illuminate\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Http\Middleware\GGG::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\III::class,
    ]);
})

Registering Middleware Groups

Next, here is how to group multiple middlewares under a single key and assign them to routes.

Laravel 10

Middleware to be executed is specified in the $middlewareGroups property of app/Http/Kernel.php.

https://github.com/laravel/laravel/blob/v10.3.3/app/Http/Kernel.php#L31-L46

By default, two middleware groups, web and api, are defined.
These two middleware groups automatically load the corresponding web and api route files in app/Providers/RouteServiceProvider.php.

https://github.com/laravel/laravel/blob/v10.3.3/app/Providers/RouteServiceProvider.php#L25-L39

You can change the execution order or specify custom middleware by modifying the elements of the web and api arrays in the $middlewareGroups property.

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\VerifyCsrfToken::class, // Change the order so CSRF token check runs first
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\AAA::class, // Add custom middleware
        ],

        'api' => [
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

Also, you can add new middleware groups.
The added middleware group can then be assigned to routes.

    protected $middlewareGroups = [
        'web2' => [
            \App\Http\Middleware\AAA::class,
            \App\Http\Middleware\BBB::class,
            \App\Http\Middleware\CCC::class,
        ],
    ];
Route::get('/', function () {
    // ...
})->middleware('web2');
    public function boot(): void
    {
        $this->routes(function () {
            Route::middleware('web2')
                ->group(base_path('routes/web2.php'));
        });
    }

Laravel 12

Similar to registering middleware, you register middleware groups using the withMiddleware method in bootstrap/app.php.
Also, like Laravel 10, web and api are defined as default middleware groups.

https://github.com/laravel/framework/blob/12.x/src/Illuminate/Foundation/Configuration/Middleware.php#L482-L500

To register custom middleware in these groups, use the web and api methods defined in the Illuminate\Foundation\Configuration\Middleware class, which is passed as an argument to the closure in the withMiddleware method.

use App\Http\Middleware\AAA;
use App\Http\Middleware\BBB;

->withMiddleware(function (Middleware $middleware) {
    // Add to the end of the web middleware group
    $middleware->web(append: [
        AAA::class,
    ]);

    // Add to the beginning of the api middleware group
    $middleware->api(prepend: [
        BBB::class,
    ]);
})

Also, you can use replace to swap default middleware.
Furthermore, to remove default middleware, use remove.

use App\Http\Middleware\GGG;
use Illuminate\Foundation\Http\Middleware\TrimStrings;
use Illuminate\Http\Middleware\ValidatePostSize;

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(replace: [
        TrimStrings::class, GGG::class
    ]);

    $middleware->web(remove: [
        ValidatePostSize::class,
    ]);
})

Also, you can register middleware groups using the group method.

use App\Http\Middleware\AAA;
use App\Http\Middleware\BBB;

->withMiddleware(function (Middleware $middleware) {
    // Add to the end of the web middleware group
    $middleware->group('web2' [
        AAA::class,
        BBB::class,
    ]);
})

Registering Aliases

This is how to assign aliases to middleware.

Laravel 10

In app/Http/Kernel.php, specify the middleware you want to alias in the $middlewareAliases property.

Several are registered by default.

https://github.com/laravel/laravel/blob/v10.3.3/app/Http/Kernel.php#L55-L67

    protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
        'signed' => \App\Http\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'aaa' => \App\Http\Middleware\AAA::class,   // Specify custom middleware
    ];

Laravel 12

Similar to registering middleware, you can set middleware aliases using the withMiddleware method in bootstrap/app.php.

Like Laravel 10, several are registered by default.

https://github.com/laravel/framework/blob/12.x/src/Illuminate/Foundation/Configuration/Middleware.php#L779-L802

To actually set them, use the alias method defined in the Illuminate\Foundation\Configuration\Middleware class, which is passed as an argument to the closure in the withMiddleware method.

use App\Http\Middleware\AAA;

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'aaa' => AAA::class
    ]);
})

Summary

I have organized the changes regarding middleware configuration in Laravel 11 and later.
As I was writing this, I realized how much has changed. It makes sense that the upgrade guide recommends against changing the application structure when upgrading versions.

https://laravel.com/docs/11.x/upgrade#application-structure

There are likely other changes as well, so I intend to add more information as I notice them.

GitHubで編集を提案

Discussion