Laravel Multi-language Route Prefix

258 Views Asked by At

I managed to get some routes working with and without a prefix. Having routes that do not have the prefix work properly is important as it's too much work to go back and change all get/post links to the correct localized ones.

For example with the code below the URL localhost/blog redirects to localhost/en/blog (or any other language stored in session).

However, I noticed that URLs with parameters don't work, so /blog/read/article-name will result in a 404 instead of redirecting to /en/blog/read/article-name.

Routes:

Route::group([
    'prefix' => '{locale}',
    'middleware' => 'locale'],
    function() {
        Route::get('blog', 'BlogController@index');
        Route::get('blog/read/{article_permalink}', 'BlogController@view');
    }
);

Middleware is responsible for the redirects which don't seem to fire at all for some routes as if the route group isn't matching the URL.

public function handle($request, Closure $next)
{
    if ($request->method() === 'GET') {
        $segment = $request->segment(1);

        if (!in_array($segment, config('app.locales'))) {
            $segments = $request->segments();
            $fallback = session('locale') ?: config('app.fallback_locale');
            $segments = array_prepend($segments, $fallback);

            return redirect()->to(implode('/', $segments));
        }

        session(['locale' => $segment]);
        app()->setLocale($segment);
    }

    return $next($request);
}
0

There are 0 best solutions below