lundi 2 mai 2016

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);
}

}

Thank you for you help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire