Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getFallbackLocale method #391

Merged

Conversation

gdebrauwer
Copy link
Contributor

In a project I'm working on, my models have translatable attributes but also a 'fallback_locale' attribute. If for example the title of the model does not have a translation in the user's current locale, then it should use the translation in the 'fallback_locale' that is set on the model (instead of a global fallback locale that is set for entire application). To support this behavior, this PR adds the option to define a getFallbackLocale method on a model

class Article extends Model
{
    use HasTranslations;

	protected $translatable = [
       'title',
    ];

    public function getFallbackLocale() : string
    {
        return $this->fallback_locale; // a column/attribute on the model
    }
}
$article->setTranslation('title', 'fr', 'french title');
$article->setTranslation('title', 'en', 'english title');
$article->forceFill(['fallback_locale' => 'fr']);

config()->set('app.fallback_locale', 'en');

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

// The french translation is returned because no dutch translation exist
dump($article->title);

@freekmurze
Copy link
Member

Looks good!

Could you also add an example for this in the readme?

@gdebrauwer
Copy link
Contributor Author

✅ done

@freekmurze freekmurze merged commit b8f1024 into spatie:main May 6, 2023
@freekmurze
Copy link
Member

Perfect, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants