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

[feature] elegant syntax update #229

Merged
merged 4 commits into from
Oct 2, 2020
Merged

[feature] elegant syntax update #229

merged 4 commits into from
Oct 2, 2020

Conversation

angauber
Copy link
Contributor

@angauber angauber commented Oct 1, 2020

This is an attempt at making this package more elegant / easy to use.

The default locale when using the model accessor is the app locale,
In some cases you might need to get / set translations with a custom locale and if you do so the accessor is not usable without overriding the app locale.

In most cases you could just override the app locale for a short period of time but this feels dirty.

Instead of using the app locale this PR adds a $locale property on the trait that is used instead of the app locale when set.

That makes it possible to use the accessor with any locale.

Example:
Imagine you want to save some data with the orm through a method:

Model:

// Model
class Item extends Model
{
    use HasTranslations;

    protected $fillable = ['name', 'info', 'state', 'comment'];

    public $translatable = ['name', 'info'];
}

Old way of doing it:

public function createTranslated($data, $locale)
{
    $test = new Test();

    $test->fill(Arr:except($data, $this->translatable));

    $test->setTranslations($locale, Arr::only($this->translatable))

    $test->save()
}

Or

    public function createTranslated($data, $locale)
    {
        $item = new Item();

        $buff = App::getLocale();
        App::setLocale($locale);

        $item->fill($data);

        $item->save();

        App::setLocale($buff);
    }

New way:

    public function createTranslated($data, $locale)
    {
        Item::withLocale($locale)->create($data);
    }

This is just a basic example that shows what issue this PR tries to overcome

src/HasTranslations.php Outdated Show resolved Hide resolved
@freekmurze freekmurze merged commit d265055 into spatie:master Oct 2, 2020
@freekmurze
Copy link
Member

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