Skip to content

Instantly share code, notes, and snippets.

@elnurxf
Created April 22, 2019 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elnurxf/7e36bb81f8c22e9d2b38e1cf67d7d47f to your computer and use it in GitHub Desktop.
Save elnurxf/7e36bb81f8c22e9d2b38e1cf67d7d47f to your computer and use it in GitHub Desktop.
<?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