nonsensei
nonsensei

Reputation: 480

Laravel 5.2 nested route groups with middleware

Problems:

  1. Session::flash won't work
  2. Weird route parameters

Problem 1

I'm experiencing a bug where Session::flash won't work. I also found a workaround but it's.. weird.

I think there's something wrong with nested groups and middlewares.

Code:

Route::group(['middleware' => 'web'], function () {
    Route::group([
            'prefix' => '{locale}',
            'middleware' => ['localized']
        ], function($locale)
    {
        Route::resource('/', 'ProductController', ['only' => ['index']]);
        Route::get('/cart', 'CartController@show')->name('show-shopping-cart');
    });

    Route::patch('/cart', 'CartController@update')->name('patch-cart');
});

now.. this will work if I modify kernel.php this way:

from

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];

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

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

to

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
];

protected $middlewareGroups = [
    'web' => [
    ],

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

what do you think about it?

Problem 2

In the routes above, ProductController@show is getting 2 parameters: locale and id.

For example if I navigate to /en/4

function show($id){
    dd($id);
}

$id = "en"

it would work this way:

function show($locale, $id){
    dd($id);
}

is this by design? If so is there a way to avoid the $locale being passed to routes inside the group?

Upvotes: 4

Views: 3030

Answers (1)

nonsensei
nonsensei

Reputation: 480

Found the answer

https://stackoverflow.com/a/36298013/4805056

the original post says to replace

Route::group(['middleware' => ['web']], function () {
   ...
});

with

Route::group(['middlewareGroups' => ['web']], function () {
   ...
});

Upvotes: 1

Related Questions