Fallback Translations - nevadskiy/laravel-translatable GitHub Wiki
Sometimes the translation of the model to some locale may be missing.
In such cases, instead of an empty value, the translator will return the translation to the fallback locale.
To make this easy to do, the strategy will be eager load translations for the current and fallback locales when querying translatable models from the database.
Also, the Nevadskiy\Translatable\Events\TranslationMissing
event will be triggered for missing translations, which you can use for example to log that the translation needs to be added.
Custom fallback behaviour
You can use your behavior to fallback missing translations using the getOr method.
Custom fallback locale
By default, the translator gets a fallback locale from the app.fallback_locale
configuration.
You can change this rule by giving the translator your own function to determine the fallback locale in the boot
method of your AppServiceProvider
:
use Nevadskiy\Translatable\Translator;
...
Translator::resolveFallbackLocaleUsing(function () {
return 'uk';
});
Custom fallback locale per model
You can also specify a different fallback locale for different models.
To do this, configure the translator in the model using the configureTranslator
hook as follows:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Nevadskiy\Translatable\Strategies\ExtraTable\HasTranslations;
class Book extends Model
{
use HasTranslations;
protected function configureTranslator(Translator $translator): void
{
$translator->fallbackLocale('uk');
}
}
Disabling fallback translations
It is possible to disable the fallback behavior for a specific model.
In this case, when the translation is missing, a null
value will be returned.
Also, translations for fallback locales will not be eager loaded, only translations to the current locale will be loaded.
To do it, you need using the configureTranslator
hook:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Nevadskiy\Translatable\Strategies\ExtraTable\HasTranslations;
class Book extends Model
{
use HasTranslations;
protected function configureTranslator(Translator $translator): void
{
$translator->disableFallback();
}
}
Fallback method
You can directly get the attribute translation to the fallback locale using the getFallback
method:
echo $book->translator()->getFallback('title');