Search code examples
laravel-5locale

How to detect language preference in Laravel 5


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 country name current user opened like "en-jp" or "japan".

I try this code but it seems to display the language that I previously selected and by default it's English.

I set a Middleware and I need to exclude the api part because I have some routers pinging this address and router browser does not have language information which brick the system.

class BeforeMiddleware
{

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Closure $next
 * @return mixed
 */

protected $except_urls = [
    'api/*'
];

public function handle($request, Closure $next)
{
    $langArr = array("en", "fr");
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    } else {
        $languages[0] = "en";
    }
    if (Session::has('locale')) {
        App::setLocale(Session::get('locale'));
    } else {
        if (in_array($languages[0], $langArr))
            App::setLocale($languages[0]);
    }
    return $next($request);
}


} /* end class */

Thank you for you help.


Solution

  • To simply get the locale from the header, you can grab the http-accept-language value from the request. This is accessible via a facade or you can use the request variable in your middleware:

    Request::server('HTTP_ACCEPT_LANGUAGE')
    
    // OR
    
    $request->server('HTTP_ACCEPT_LANGUAGE');
    

    This returns a string which looks like this: en-GB,en;q=0.8. You can then parse it (perhaps using explode()?) and grab the language from there.

    However, this sort of thing can sometimes get complicated. If you need to do something more advanced, there's a package which can do all of this for you:

    https://github.com/mcamara/laravel-localization