Skip to content

Commit

Permalink
Fix attribute mutators
Browse files Browse the repository at this point in the history
  • Loading branch information
vencelkatai authored and freekmurze committed Dec 11, 2024
1 parent 7d97397 commit fc3f318
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/HasTranslations.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public function translate(string $key, string $locale = '', bool $useFallbackLoc
public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed
{
// if column value is `null` then we have nothing to do, return `null`
if (is_null(parent::getAttributeValue($key))) {
if (is_null(parent::getAttributeFromArray($key))) {
return null;
}

Expand Down
22 changes: 22 additions & 0 deletions tests/TranslatableTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use Illuminate\Database\Eloquent\Casts\Attribute as Attribute;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Storage;
use Spatie\Translatable\Exceptions\AttributeIsNotTranslatable;
Expand Down Expand Up @@ -528,6 +529,27 @@ public function setNameAttribute($value)
expect($testModel->getTranslations('field_with_mutator'))->toEqual($translations);
});

it('uses the attribute to mutate the translated value', function () {
$testModel = (new class () extends TestModel {
public $mutatedValues = [];

protected function name(): Attribute
{
return Attribute::get(function ($value) {
$this->mutatedValues[] = $value;

return 'mutated';
});
}
});

$testModel->name = 'hello';
$testModel->save();

expect($testModel->name)->toEqual('mutated');
expect($testModel->mutatedValues)->toBe(['hello']);
});

it('can translate a field based on the translations of another one', function () {
$testModel = (new class () extends TestModel {
public function setOtherFieldAttribute($value, $locale = 'en')
Expand Down

0 comments on commit fc3f318

Please sign in to comment.