Localization without route prefix doesn't work

- 1 answer

Ad

I'm using the Laravel docs to implement localization (without the prefix in the url).

Basically I want two links "EN" and "NL". Depending on which link I click, the locale should be changed to that specific language.

I use this links:

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="/language/benl">NL</a>
<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="/language/en">EN</a>

This route:

Route::get('language/{locale}', '[email protected]');

And this is my HomeController:

class HomeController extends Controller
{

    public function setLang($locale){
        App::setLocale($locale);
        return back();
    }
}

I set my files in resources/lang the way it's explained in the docs. But, the output ( {{ trans('messages.welcome') }} ) isn't translated.

What am I doing wrong? :)

UPDATE

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="/auth/register">{{ trans('header.register') }}</a>

Routes

Route::group(['middleware' => ['language']], function () {
    //
    Route::get('language/{locale}', '[email protected]');

});

Lang file:

return [
    'register' => 'REGISTREER',
];

My Kernel.php

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'language' => \App\Http\Middleware\Language::class,
    ];
Ad

Answer

Ad

If you don't want to prefix the urls, you could use the session in conjunction with a middleware.

All you need is a controller and a middleware.

App\Http\Controllers\HomeController method:

class HomeController extends Controller
{
    public function setLang($locale)
    {
        // 1. store selected locale
        Session::put('my_project.locale', $locale);

        return back();
    }
}

App\Http\LocaleMiddleware method:

class LocaleMiddleware
{
    public function handle($request, Closure $next)
    {
        $default = config('app.locale');

        // 2. retrieve selected locale if exist (otherwise return the default)
        $locale = Session::get('my_project.locale', $default);

        // 3. set the locale
        App::setLocale($locale);

        return $next($request);
    }
}

Do not forget to register the middlewareglobally.

Ad
source: stackoverflow.com
Ad