How to detect language preference in Laravel 5

后端 未结 5 1153
野的像风
野的像风 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:37

    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

提交回复
热议问题