Astrotomic / laravel-translatable

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

Problem with use_property_fallback - returns null. #278

Closed PitchRE closed 2 years ago

PitchRE commented 2 years ago

As title;

Config


    'locales' => [
        'en_US',
        'ja_JP',
        'pl_PL'

    ],

  'locale' => null,
   'use_fallback' => true,
 'use_property_fallback' => true,
'fallback_locale' => 'en_US',

Code


    app()->setLocale('en_US');
    $item = Item::factory()->create();

    app()->setLocale('ja_JP');

    $item->update(['ja_JP' => [
        'name' => Item::factory()->make()->name
    ]]);

    //// slug for ja_JP is always null;

    return $item->translate('ja_JP', true);

Output

{
"locale": "ja_JP",
"name": "加納 裕太",
"item_id": 22,
"id": 43
}

I excepted 'slug' and 'description' property to not be null.

$item->getTranslationsArray() outputs

{
"en_US": {
"name": "Jazlyn Kunze",
"description": "Minus eos et nulla quia sint vel vel eveniet. Enim dolor omnis quod quia quos nihil ipsum. Odio et cum quis praesentium ut et perferendis. Mollitia sint debitis at. Ut magnam quia dolorum qui.",
"slug": "jazlyn-kunze"
},
"ja_JP": {
"name": "小林 美加子",
"description": null,
"slug": null
}
}

What do I do incorrectly?

Gummibeer commented 2 years ago

translate() returns the translation model instance - which will be ja_JP as requested. If you want to use the property fallback you should use $item->slug - these will use the property fallback as you request a specific model attribute.

PitchRE commented 2 years ago

Thank you for clarification. So I guess there is no way to make use of property fallback feature without changing locale globally in the app?

Gummibeer commented 2 years ago

You can also pass the locale as part of the attribute $post->{'title:de'}. https://docs.astrotomic.info/laravel-translatable/usage/attributes