Astrotomic / laravel-translatable

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

Fallback not taking into account public defaultLocale prop #197

Closed tomvo closed 3 years ago

tomvo commented 3 years ago

Here's our situation, our fallback_locale is DE. We have one model called Post which dynamically changes the default locale based on a column in the database (primary_language), depending on the language the user wrote the post in. Like so:

public function __construct(array $attributes = array())
    {
      ...

        $this->defaultLocale = $this->primary_language;
    }

This works fine. However, a Post can have multiple translations (doesn't necessarily have) and I want to render the Post in the current locale if that is available, otherwise fallback to primary_language.

I assumed I could use this: $route->translateOrDefault(app()->getLocale())->name However, the translateOrDefault only falls back to the fallback_locale, not the locale set as defaultLocale for that model at runtime.

Is this intended behaviour?

Gummibeer commented 3 years ago

Hey,

the behavior is all right but I understand your confusion and it will be fixed/removed with v12.

The defaultLocale is used in the locale() method which should return the "normal"/intended locale. https://github.com/Astrotomic/laravel-translatable/blob/b4201e5500572955c2dd8a636da75ad555d37070/src/Translatable/Translatable.php#L353-L360

As you pass a locale to translateOrDefault() the locale() method isn't called. https://github.com/Astrotomic/laravel-translatable/blob/b4201e5500572955c2dd8a636da75ad555d37070/src/Translatable/Translatable.php#L189-L194

The fallback locale doesn't use the defaultLocale in any way. https://github.com/Astrotomic/laravel-translatable/blob/b4201e5500572955c2dd8a636da75ad555d37070/src/Translatable/Translatable.php#L414-L423

The defaultLocale isn't a default/fallback but an enforced locale. I also see an issue in the decision for private methods as you aren't able to easily adjust the logic. I will work on a fix that switches the methods to protected so you can customize the fallback locale logic.

tomvo commented 3 years ago

@Gummibeer Awesome! Thanks a lot for your extended reply. Any idea on when you can merge and tag the PR?

Gummibeer commented 3 years ago

https://github.com/Astrotomic/laravel-translatable/releases/tag/v11.9.1

tomvo commented 3 years ago

@Gummibeer 🙌