Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Created March 23, 2020 13:51
Show Gist options
  • Save tobiashm/8fba5630ffe1f6395c8e0ea55ec3bdf8 to your computer and use it in GitHub Desktop.
Save tobiashm/8fba5630ffe1f6395c8e0ea55ec3bdf8 to your computer and use it in GitHub Desktop.
Custom Laravel Translator that handles locale with region

In config/app.php in the 'providers' section, replace Illuminate\Translation\TranslationServiceProvider::class with App\Translation\TranslationServiceProvider::class

<?php
namespace App\Translation;
class TranslationServiceProvider extends \Illuminate\Translation\TranslationServiceProvider
{
public function register(): void
{
$this->registerLoader();
$this->app->singleton('translator', function ($app) {
$loader = $app['translation.loader'];
// When registering the translator component, we'll need to set the default
// locale as well as the fallback locale. So, we'll grab the application
// configuration so we can easily get both of these values from there.
$locale = $app['config']['app.locale'];
$trans = new Translator($loader, $locale);
$trans->setFallback($app['config']['app.fallback_locale']);
return $trans;
});
}
}
<?php
namespace App\Translation;
class Translator extends \Illuminate\Translation\Translator
{
/**
* Get the array of locales to be checked.
*
* @param string|null $locale
*
* @return array
*/
protected function localeArray($locale)
{
$locale = $locale ?: $this->locale;
$language = locale_get_primary_language($locale);
return array_filter([$language ?: $locale, $this->fallback]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment