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