Skip to content

Commit

Permalink
Fix dirty translatable attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
acasar committed Oct 24, 2016
1 parent 9d90606 commit 3215a72
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Translatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ trait Translatable

protected $overrideWithFallback = null;

protected $localeChanged = false;

/**
* Translated attributes cache
*
Expand Down Expand Up @@ -287,6 +289,8 @@ public function setLocale($locale)
{
$this->overrideLocale = $locale;

$this->localeChanged = true;

return $this;
}

Expand Down Expand Up @@ -464,4 +468,38 @@ protected function newBaseQueryBuilder()

return $builder->setModel($this);
}

/**
* Get the attributes that have been changed since last sync.
*
* @return array
*/
public function getDirty()
{
$dirty = parent::getDirty();

if(! $this->localeChanged) {
return $dirty;
}

foreach ($this->translatableAttributes() as $key) {
if(isset($this->attributes[$key])) {
$dirty[$key] = $this->attributes[$key];
}
}

return $dirty;
}

/**
* Sync the original attributes with the current.
*
* @return $this
*/
public function syncOriginal()
{
$this->localeChanged = false;

return parent::syncOriginal();
}
}
13 changes: 13 additions & 0 deletions tests/TestCRUD.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,19 @@ public function testModelCanBeStoredAndRetrievedInDifferentLocales()
$this->assertEquals('DE Lorem ipsum', $user->bio);
}

public function testModelWithIdenticalTranslationsIsSaved()
{
User::forceCreate([
'name' => 'John Doe'
], [
'en' => ['bio' => 'Sample bio'],
'de' => ['bio' => 'Sample bio'],
]);

$this->assertEquals('Sample bio', User::withoutFallback()->onlyTranslated('en')->first()->bio);
$this->assertEquals('Sample bio', User::withoutFallback()->onlyTranslated('de')->first()->bio);
}

public function testFallbackLocaleIsUsedWhenNoMatchingLocaleIsFound()
{
User::forceCreate([
Expand Down

0 comments on commit 3215a72

Please sign in to comment.