Search code examples
phplaravel-5routesmiddleware

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


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);
}

Solution

  • 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');
            });
        }
    }