Created
January 11, 2017 13:16
-
-
Save gbaudoin/cfb69db066f46de179d1917b982f1a9c to your computer and use it in GitHub Desktop.
Browser language detection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Carbon\Carbon; | |
/** | |
* Class LocaleMiddleware. | |
*/ | |
class LocaleMiddleware | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
/* | |
* Locale is enabled and allowed to be changed | |
*/ | |
if (config('locale.status')) { | |
// Do we have a session locale ? | |
if(session()->has('locale')) { | |
$locale_temp = session()->get('locale'); | |
if(in_array($locale_temp, array_keys(config('locale.languages')))) { | |
$locale = $locale_temp; | |
} | |
} else { | |
// Else, get the browser locale | |
$locale_temp = substr(locale_accept_from_http($request->server('HTTP_ACCEPT_LANGUAGE')), 0, 2); | |
if(in_array($locale_temp, array_keys(config('locale.languages')))) { | |
$locale = $locale_temp; | |
} | |
} | |
if (isset($locale)) { | |
/* | |
* Set the Laravel locale | |
*/ | |
app()->setLocale($locale); | |
/* | |
* setLocale for php. Enables ->formatLocalized() with localized values for dates | |
*/ | |
setlocale(LC_TIME, config('locale.languages')[$locale][1]); | |
/* | |
* setLocale to use Carbon source locales. Enables diffForHumans() localized | |
*/ | |
Carbon::setLocale(config('locale.languages')[$locale][0]); | |
/* | |
* Set the session variable for whether or not the app is using RTL support | |
* for the current language being selected | |
* For use in the blade directive in BladeServiceProvider | |
*/ | |
if (config('locale.languages')[$locale][2]) { | |
session(['lang-rtl' => true]); | |
} else { | |
session()->forget('lang-rtl'); | |
} | |
} | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment