In Laravel when is the number of URL segments more than one, middleware don't run in RouteGroup

Viewed 493

I need to add the location to all URLs. I used "mapWebRoutes" in "RouteServiceProvider.php" like this:

    protected function mapWebRoutes()
{
    $locale = Request::segment(1);
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
        'prefix' => $locale
    ], function ($router) {
        require base_path('routes/web.php');
    });
}

But when is the number of segments more than one, middleware doesn't run. For example, the location is added correctly to the address below.

http://example.com/test after return from middleware => http://example.com/en/test

But location is not added to the address below:

http://example.com/test1/test2

This means that the middleware has not been Run. I add echo 'test'; exit(); to the first line of middleware to make sure the middleware is running. But when is the number of segments more than one, middleware doesn't run.

My Middleware code is:

    public function handle($request, Closure $next)
{
    if (!array_key_exists($request->segment(1), config('translatable.locales'))) {
        // Store segments in array
        $segments = $request->segments();
        // Set the default language code as the first segment
        $segments = array_prepend($segments, config('app.fallback_locale'));

        // Redirect to the correct url
        return redirect()->to(implode('/', $segments));
    }
    return $next($request);
}
2 Answers

I changed mapWebRoutes() to below code and problem sloved:

 protected function mapWebRoutes()
{
    if (!array_key_exists(Request::segment(1), config('translatable.locales'))) {
        Route::group([
            'middleware' => ['web'],
            'namespace' => $this->namespace
        ], function ($router) {
            require base_path('routes/web.php');
        });
    } else {
        $locale = Request::segment(1);
        Route::group([
            'middleware' => ['web'],
            'namespace' => $this->namespace,
            'prefix' => $locale
        ], function ($router) {
            require base_path('routes/web.php');
        });
    }
}

Thank you. I followed your idea an added a condition too.

I have this in my mapWebRoutes method:

if (!Language::isValid($locale))
    $locale = '';

Route::middleware(['web', 'lang'])
    ->namespace($this->namespace)
    ->prefix($locale)
    ->group(function () {
        require base_path('routes/web/test.php');
        require base_path('routes/web/general.php');
        require base_path('routes/web/blog.php');
        require base_path('routes/web/payments.php');
    });

If the language is not valid, an empty value omit the prefix and calls the middleware as well.

Related