How to detect language preference in Laravel 5

后端 未结 5 1176
野的像风
野的像风 2020-12-31 12:42

I want to detect my client language by getting the browser recommended language.

For Example, if you open the browser in Japan it will give me country code or countr

5条回答
  •  失恋的感觉
    2020-12-31 13:38

    I just made a Middleware for this, it may be useful.

    First you set $availableLangs the array of the available languages in your app, you may use config\app.php instead of initializing the array in the middleware as I did.

    If the first language is available in the request language data, it sets the locale, if not, it will search the next one, and so on.

    class GetRequestLanguage
    {
    
        public function handle($request, Closure $next)
        {
            if (Session::has('locale')) {
                App::setLocale(Session::get('locale'));
            } else {
                $availableLangs = ['pt', 'en'];
                $userLangs = preg_split('/,|;/', $request->server('HTTP_ACCEPT_LANGUAGE'));
    
                foreach ($availableLangs as $lang) {
                    if(in_array($lang, $userLangs)) {
                        App::setLocale($lang);
                        Session::push('locale', $lang);
                        break;
                    }
                }
            }
    
            return $next($request);
        }
    }
    

提交回复
热议问题