Astrotomic / laravel-translatable

A Laravel package for multilingual models
https://docs.astrotomic.info/laravel-translatable/
MIT License
1.24k stars 156 forks source link

Translate multiple model items without using App::setLocale() #386

Closed overclocked555 closed 7 months ago

overclocked555 commented 7 months ago

Thanks a lot for the great package!

Is there a way to translate multiple model items into a specific language at once without using App::setLocale()? So far I only see this complicated method:

App::currentLocale(); // en

$posts = Post::with('translations')->get();
foreach ($posts as $post) {
    $post->title = $post->translateOrDefault('de')->title;
}

And after that I will have to prevent the models from being translated when converted to JSON or array.

Method with App::setLocale() :

$savedLocale = App::currentLocale(); // en
App::setLocale('de');
Post::withTranslation()->get()->toArray();
App::setLocale($savedLocale);

But I doubt if such code is executed in Blade Anonymous Components, whether changing the locale will affect other parts of the application.

Any ideas?

Gummibeer commented 7 months ago

Hey, you can use $post->{'title:de'} to get the attribute in a specific locale. https://docs.astrotomic.info/laravel-translatable/usage/attributes https://github.com/Astrotomic/laravel-translatable/blob/0ead23494acb289af594427503f3749513891749/src/Translatable/Translatable.php#L384-L391

Besides that you can also set the locale to be used on a per model level $post->setDefaultLocale('de') - this will set a property on the model instance and won't affect anything else. To undo it just call the method with a null argument. https://github.com/Astrotomic/laravel-translatable/blob/0ead23494acb289af594427503f3749513891749/src/Translatable/Translatable.php#L353-L360

overclocked555 commented 7 months ago

Thanks a lot for the tips!