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

trogne's avatar

assign middleware to only api group

The laravel doc is unclear on how to assign a middleware to only a group.

Here a "cors" middleware in Kernel.php:

        'api' => [
            'throttle:60,1',
            'bindings',
            'cors'
        ],
    ];

    protected $routeMiddleware = [
    //...
        'cors' => Cors::class
    ];

Using this, my api route (in "routes/api.php") does not trigger my cors middleware.

It only works if I use it globally in protected $middleware = []

My api route is supposed to use the "api" group. Why my "cors" middleware is not triggered ?

    protected function mapApiRoutes()
    {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));
    }
0 likes
5 replies
trogne's avatar

If I use the same origin on front and back end, then my cors middleware is hit. But with different origins, it seems that the cors is blocked before reaching my own cors middleware...

PWParsons's avatar

Hi @trogne,

Can you try this in Kernel.php...

protected $routeMiddleware = [
     //...
     'cors' => Cors::class
];

and in your api routes...

Route::group(function () {
    //...
})->middleware('cors');
trogne's avatar

This is not working. Routes defined "routes/api.php" is already using a group, "api" in Kernel.php

In my case the request is blocked (cors reject) before reaching the first api group middleware. My conclusion is that, as of laravel 6.6.1, it's still not possible to handle cors in a middleware group. The cors middleware must be added to the $middleware array (global middlewares).

Further, your "Route::group" will return null in your case.

PWParsons's avatar

Apologies, I misunderstood your question. I thought you were trying to apply the middleware to a group within the api routes.

The route group in my previous answer will return null because it was only an example.

What you are doing in your Kernel is correct. Maybe something else is wrong?

I tested the following in Laravel 6.6.2 and it works fine:

protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        'bindings',
        'cors',
    ],
];

protected $routeMiddleware = [
    'cors' => \Barryvdh\Cors\HandleCors::class,
];
trogne's avatar

Oh, I wanted to test barryvdh/laravel-cors, so I installed that. But now my middleware works as a group ! What happened ? Is it possible that installing barrydvh fixed something ? Did "composer require" did something with "autoload" ?

Please or to participate in this conversation.