Reading Translations - nevadskiy/laravel-translatable Wiki
To read translatable attributes, you can use the regular attributes of the model:
echo $book->title;
If the translation exists for the model, it will be successfully retrieved in the current application locale. Otherwise, the fallback translation will be used.
Translator instance
When interacting with translatable model attributes, the model internally delegates all operations to the Translator
instance (just like Eloquent does with the Builder
instance to build database queries).
But you can interact with the Translator
directly to gain more control over the translatable attributes.
There are some methods you can use to read translations:
get()
To retrieve the translation of the attribute in the current locale, use the get
method:
echo $book->translator()->get('title'); // ...
You can also retrieve the translation of the attribute in a custom locale:
echo $book->translator()->get('title', 'uk'); // ...
getOrFail()
The method works identically to the get
but when the translation is missing instead of the fallback translation the Nevadskiy\Translatable\Exceptions\TranslationMissingException
exception will be thrown.
echo $book->translator()->getOrFail('title', 'uk');
getOr()
Sometimes you want to return a custom value when the translation is missing instead of the default value in the fallback locale. To do this, you can use the getOr
method:
echo $book->translator()->getOr('title', 'uk', function () {
return 'Переклад відсутній'
});
Or for the current application locale by passing null
for the $locale
argument:
echo $book->translator()->getOr('title', null, function () {
return __('Translation is missing.')
});
getOrFallback()
...
echo $book->translator()->getOrFallback('title'); // ...
getRawOrFail()
...
echo $book->translator()->getRawOrFail('title'); // ...
has()
...
echo $book->translator()->has('title'); // ...