Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Pixelairport's avatar

Load middleware from provider in Laravel 11

Hi. I did it a lot of time, but not sure, if this was the way I did it. But when I now use

    public function boot(): void
    {
        $this->app['router']->pushMiddlewareToGroup('web', UserFlagMiddleware::class);
    }

in Laravel 11 in a provider, the middleware is not loaded. Is that the correct way for L11?

0 likes
1 reply
LaryAI's avatar
Level 58

In Laravel 11, the way to register middleware from a service provider has slightly changed. Instead of using pushMiddlewareToGroup, you should use the middlewareGroup method provided by the Router class.

Here's how you can do it:

  1. Create the Middleware: Ensure you have your middleware created. For example, UserFlagMiddleware.

  2. Register Middleware in Service Provider: In your service provider, you can register the middleware like this:

use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Router;
use App\Http\Middleware\UserFlagMiddleware;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(Router $router)
    {
        $router->middlewareGroup('web', [
            UserFlagMiddleware::class,
        ]);
    }
}

In this example, the middlewareGroup method is used to add UserFlagMiddleware to the web middleware group.

  1. Ensure Service Provider is Registered: Make sure your service provider is registered in the config/app.php file under the providers array.
'providers' => [
    // Other Service Providers

    App\Providers\AppServiceProvider::class,
],

This should correctly load your middleware into the specified group in Laravel 11.

Please or to participate in this conversation.