alex
alex

Reputation: 7895

Laravel case insensitive localization

Is it possible to make laravel case insensitive against trans statements? for example return the same translated term for both Action and action :

  lang/trans_form.php 

return [
 'Action' => 'اقدامات',

 //I'm not happy with writing this one,it would be better if laravel do it itself!
 'action' => 'اقدامات',
]

Upvotes: 2

Views: 1842

Answers (1)

Burak Ozdemir
Burak Ozdemir

Reputation: 5332

You can extend the Translator class and use it within the another extended TranslationServiceProvider class.

Lets say, we will store it in app/Extended folder.

Create an extended translator class like below. Just change the key to lowercase and pass it to the parent.

<?php

namespace App\Extended;

use Illuminate\Translation\Translator;

class ExtendedTranslator extends Translator
{
    public function get($key, array $replace = [], $locale = null, $fallback = true)
    {
        $key = mb_strtolower($key);
        return parent::get($key, $replace, $locale, $fallback);
    }
}

Then use our newly created extended Translator class within the extended TranslationServiceProvider,

<?php

namespace App\Extended;

use Illuminate\Translation\TranslationServiceProvider;

class ExtendedTranslationServiceProvider extends TranslationServiceProvider
{
    public function register()
    {
        $this->registerLoader();
        $this->app->singleton('translator', function ($app) {
            $loader = $app['translation.loader'];
            $locale = $app['config']['app.locale'];
            $trans = new ExtendedTranslator($loader, $locale);
            $trans->setFallback($app['config']['app.fallback_locale']);
            return $trans;
        });
    }
}

Finally, register the extended ExtendedTranslationServiceProvider instead of the original one within the config/app.php.

'providers' => [
    // Illuminate\Translation\TranslationServiceProvider::class,
    App\Extended\ExtendedTranslationServiceProvider::class,
]

Upvotes: 4

Related Questions