VarboxInternational / varbox

THE Laravel Admin Panel package built by developers, for developers
https://varbox.io
Other
63 stars 13 forks source link

Get translatable model attribute value in certain language #17

Closed dragosm closed 3 years ago

dragosm commented 3 years ago

What are you trying to achieve (screenshots might help):

Hey,

I have a News custom entity on which I've applied the HasTranslations trait in order to support title and content in multiple languages.
Everything works great and the admin crud also supports multi-language.

Also, in my frontend I've noticed that by accessing $news->title (just normal Laravel syntax) returns the value for the locale I'm currently on.

I was wondering if for example I could get the title in English, even if my locale is set to fr.

Thanks! Great work creating this package!

zbiller commented 3 years ago

Yes, it is possible to get any attribute's value in any of the supported languages, regardless of your set locale, by using the getTranslation method.

$news = News::find($id);

$titleInEnglish = $news->getTranslation('title', 'en');

Here's the doc section for reference: https://varbox.io/docs/2.x/translatable-models#get-translation


Also, regarding what you've said that accessing $news->title returns the value for the locale you're currently set to, yes, that's true.

That's done inside the Varbox\Traits\HasTranslations trait, namely inside the getAttribute method (which actually uses the same getTranslation method, but with your set locale by default).

This is done to ease the implementation process, thus keeping it Laravel friendly :)