Created
April 22, 2019 11:52
-
-
Save elnurxf/7e36bb81f8c22e9d2b38e1cf67d7d47f to your computer and use it in GitHub Desktop.
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 | |
/** | |
* | |
* Detect country based on CloudFlare HTTP_CF_IPCOUNTRY headers | |
* Set Default language for specific region | |
* | |
* See: https://support.cloudflare.com/hc/en-us/articles/205072537 | |
*/ | |
namespace App\Http\Middleware; | |
use App; | |
use Closure; | |
use LaravelLocalization; | |
class DefaultLocale | |
{ | |
public function handle($request, Closure $next) | |
{ | |
// Get locale from URL | |
$url_locale = $request->segment(1); | |
$supported_locales = config('laravellocalization.supportedLocales'); | |
// If locale code already exists and valid | |
if (in_array($url_locale, array_keys($supported_locales))) { | |
return $next($request); | |
} | |
// Get country code | |
$country = $request->server('HTTP_CF_IPCOUNTRY'); | |
$country = strtoupper($country); | |
$appLocale = App::getLocale(); | |
// Country -> Locale | |
$mapping = collect([ | |
'RU' => 'ru', | |
'UA' => 'ru', | |
'BE' => 'ru', | |
'KZ' => 'ru', | |
'UZ' => 'ru', | |
'US' => 'en', | |
'UK' => 'en', | |
'GE' => 'en', | |
'DE' => 'en', | |
'IR' => 'en', | |
'FR' => 'en', | |
'IN' => 'en', | |
'AE' => 'en', | |
'AZ' => 'az', | |
'TR' => 'az', | |
]); | |
if ($mapping->has($country)) { | |
$country_locale = $mapping->get($country); | |
if ($country_locale != $appLocale) { | |
LaravelLocalization::setLocale($country_locale); | |
App::setLocale($country_locale); | |
} | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment