Skip to content

Commit

Permalink
Fix toArray when using accessors on translatable attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
vencelkatai committed Feb 29, 2024
1 parent 71f9f36 commit 4e897c7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/HasTranslations.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ public function getAttributeValue($key): mixed
return $this->getTranslation($key, $this->getLocale(), $this->useFallbackLocale());
}

protected function mutateAttributeForArray($key, $value): mixed
{
if (! $this->isTranslatableAttribute($key)) {
return parent::mutateAttributeForArray($key, $value);
}

$translations = $this->getTranslations($key);

return array_map(fn ($value) => parent::mutateAttributeForArray($key, $value), $translations);
}

public function setAttribute($key, $value)
{
if ($this->isTranslatableAttribute($key) && is_array($value)) {
Expand Down
19 changes: 19 additions & 0 deletions tests/TranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,25 @@ public function getNameAttribute($value): string
expect('I just accessed testValue_en')->toEqual($testModel->name);
});

it('can be converted to array when using accessors on translated attributes', function () {
$testModel = new class () extends TestModel {
public function getNameAttribute($value)
{
return "I just accessed {$value}";
}
};

$testModel->setTranslation('name', 'en', 'testValue_en');
$testModel->setTranslation('name', 'nl', 'testValue_nl');

expect($testModel->toArray())
->toHaveKey('name')
->toContainEqual([
'en' => 'I just accessed testValue_en',
'nl' => 'I just accessed testValue_nl',
]);
});

it('can use mutators on translated attributes', function () {
$testModel = new class () extends TestModel {
public function setNameAttribute($value)
Expand Down

0 comments on commit 4e897c7

Please sign in to comment.