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

Fix toArray when using accessors on translatable attributes #437

Merged
merged 1 commit into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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')
->toContain([
'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
Loading