Search code examples
phplaravellaravel-routing

Laravel: Replacing middleware parameters in nested routes


I have a Route group which applies middlewares to all nested routes. I am passing a parameter to it.

Inside the group, though, I have a specific route for which I want to pass a different parameter. Which I do as following:

Route::group(['prefix' => '/' . $languagePrefix, 'middleware' => ['sessionapi', 'abtest:0']], function () {

// other routes

Route::get('/i18n', [
    'as' => 'api:i18n',
])->middleware('abtest:1');

}

But in the middleware handle itself, the parameter is always 0, the generic one, even if I visit the route with the different parameter.

How come?

public function handle($request, \Closure $next, string $customPar = null)
{
    // ...
    dd($customPar); // always 0
    // ... 
}

I tried to use ->withoutMiddleware(['abtest'])->->middleware('abtest:1') but it didn't work


Solution

  • You can't replace abtest:0 middleware. Because, it had executed first. So you must change your route structure

    Route::group(['prefix' => '/' . $languagePrefix, 'middleware' => ['sessionapi']], function () {
        Route::middleware('abtest:0')->group( function(){
                // all routes using abtest:0
        });
    
        Route::get('/i18n', [
            'as' => 'api:i18n',
        ])->middleware('abtest:1');
    
    
    });