Search code examples
laravellocalizationmultilingual

laravel multi-language switch and change locale on load


I've implemented the language switch functionality following this post and it works perfectly but just when you click on the language switch, though I would like to change the locale and store it in the App when the page is loaded.

My function it's a bit different from the one in the post, I've added an else if just to make sure that the locale it's in the accepted languages

App/Middleware/Localization.php

public function handle($request, Closure $next)
{
    $availableLangs  = array('en', 'hu', 'pt', 'ro', 'sv');
    $userLangs = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);

    if (\Session::has('locale'))
    {
        \App::setlocale(\Session::get('locale'));
    }
    else if (in_array($userLangs, $availableLangs))
    {
        \App::setLocale($userLangs);
      // Session::push('locale', $userLangs);
    }
    return $next($request);
}

How can I reuse this function or create a new function to achieve the same result but when you load the website?

I have a lot of route so I think that I will need a function in order to don't repeat the same code over and over.

I don't use the locale on the URL and I don't want to use it, so please don't propose a solution that includes that option.

Example of my URLS (each URL can be view with all the available languages)

domain/city1/
domain/city1/dashboard/
domain/city2/
domain/city2/dashboard/
domain/admin/

I don't want:

domain/city1/en/...
domain/city1/pt/...

Solution

  • Probably you need something like this, whenever the page load initially there won't be any server value so it cannot set value for the $userLangs variable. So as per your code, the if statement fails since there is no session value and the elseif condition also fails since there is no value set for $userLangs which cannot be found in the $availableLangs. Just add one else condition to set a default lanuage of the website when there is no prefered user language.

    public function handle($request, Closure $next) 
    {
        $availableLangs  = array('en', 'hu', 'pt', 'ro', 'sv');
        $userLangs = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
    
        if (\Session::has('locale'))
        {
            \App::setlocale(\Session::get('locale'));
        }
        else if (in_array($userLangs, $availableLangs))
        {
            \App::setLocale($userLangs);
            Session::put('locale', $userLangs);
        }
        else {
            \App::setLocale('en');
            Session::put('locale', 'en');
        }
        return $next($request);
    }