Closed Nurzzzone closed 3 years ago
Post::translatedIn('en')->first()->toArray();
[
'id' => 1,
'image' => 'example/path/to/image.jpg',
'translations' => [
[
'id' => 1,
'locale' => 'en'
'title' => 'hello'
'post_id' => 1
]
]
]
but I'm getting
[
'id' => 1,
'image' => 'example/path/to/image.jpg',
'translations' => [
[
'id' => 1,
'locale' => 'en'
'title' => 'hello'
'post_id' => 1
],
[
'id' => 2,
'locale' => 'fr'
'title' => 'bonjour'
'post_id' => 1
],
[
'id' => 3,
'locale' => 'de'
'title' => 'hallo'
'post_id' => 1
]
]
]
Post::translatedIn('en')->get();
Returns all posts being translated in english https://docs.astrotomic.info/laravel-translatable/package/scopes#translatedin-string-usdlocale-null
It's just a filter scope - it doesn't interact in any way with the translation logic itself.
Also toArray()
is the worst way to do API responses - you should use explicit API Resources.
https://laravel.com/docs/8.x/eloquent-resources
@Gummibeer toArray
is just for the demonstration
It doesn't demonstrate anything - as for sure the translations
relationship is loaded and transformed to an array.
@Gummibeer so I cant get result as excepted?
Use an API resource and transform your model and relations however you want. But you should possibly use translation
(singular) or directly add the translated attributes to the resource.
$post->title
will always return the translated title for the current locale.
@Gummibeer Okay, got it. i just thought i can use this scope without creating addional classes
Like said the translatedIn()
is a plain filter scope that will filter the posts to all posts with a translation in the given locale.
After the posts are retrieved the same translate logic is used as always.
PS: please stop mentioning me all the time. I will receive a notification with a simple comment as well.
Tried both methods and gettings the same objects with all translations instead of given in scope arguments