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

RoelVB's avatar

'web' middleware group applied even if defined different

Hi all,

I'm new to Laravel and wanted to use different middleware groups for the front-end and API. For now I'm using the groups 'web' and 'api'. Now I would like to apply the 'api' middleware group to my API, but it always seem to apply the 'web' middleware.

This is what I have in my routes:

Route::group(['middleware'=>'api'], function(){
    Route::resource('api/users', 'UserController');
});

These are my middleware groups for now:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
            \App\Http\Middleware\Authenticate::class, 
        ],

        'api' => [
            //
        ],
    ];

Visiting /api/users still applies the 'web' middleware. I'm noticing that VerifyCsrf and Authenticate are active. Am I missing something?

0 likes
3 replies
gregrobson's avatar

Check your php artisan routes:list - I believe the 'web' route group is global and defined in the core of Laravel.

Best think to do is make new group that represents web routes, such as "application" and move all the middlewares from "web" into "application". Then have two groups of routes in your app - one for "application" and one for "api".

SaeedPrez's avatar

The web middleware is being applied to all routes in the RouteServiceProvider..

https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L56

Option 1

Edit RouteServiceProvider and remove the web middleware.

Option 2

protected $middlewareGroups = [
        'web' => [
            // Keep common middlewares here..
        ],

        'api' => [
            //
        ],

        'web2' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
            \App\Http\Middleware\Authenticate::class, 
        ],
    ];
RoelVB's avatar

Thanks guys. Fixed it.

I should have just used php artisan routes:list and I would have found out myself.

Please or to participate in this conversation.