Astrotomic / laravel-translatable

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

Scope translatedIn(?string $locale = null) returns the same value as Model::all() #245

Closed Nurzzzone closed 3 years ago

Nurzzzone commented 3 years ago

Tried both methods and gettings the same objects with all translations instead of given in scope arguments

dd(Post::all(), Post::translatedIn('en')->get());
Nurzzzone commented 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
          ]
    ] 
]
Gummibeer commented 3 years ago

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

Nurzzzone commented 3 years ago

@Gummibeer toArray is just for the demonstration

Gummibeer commented 3 years ago

It doesn't demonstrate anything - as for sure the translations relationship is loaded and transformed to an array.

Nurzzzone commented 3 years ago

@Gummibeer so I cant get result as excepted?

Gummibeer commented 3 years ago

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.

Nurzzzone commented 3 years ago

@Gummibeer Okay, got it. i just thought i can use this scope without creating addional classes

Gummibeer commented 3 years ago

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.

Gummibeer commented 3 years ago

PS: please stop mentioning me all the time. I will receive a notification with a simple comment as well.