Skip to content

Commit 64157c9

Browse files
authored
[Name Cast]: Don't attempt to store computed columns to the database (#12)
1 parent a1516fc commit 64157c9

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/Casts/NameCast.php

+14-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ public function __construct(protected ?string $firstName = null, protected ?stri
1818

1919
public function get($model, string $key, $value, array $attributes): Name
2020
{
21-
if ($value) {
21+
// We're probably dealing with a single column instead of a combination
22+
// of two columns.
23+
if (Arr::has($attributes, $key)) {
2224
return Name::from($value);
2325
}
2426

@@ -28,8 +30,17 @@ public function get($model, string $key, $value, array $attributes): Name
2830
return Name::from("{$firstName} {$lastName}");
2931
}
3032

31-
public function set($model, string $key, $value, array $attributes): string
33+
public function set($model, string $key, $value, array $attributes): array
3234
{
33-
return (string) $value;
35+
// We're probably dealing with a single column instead of a combination
36+
// of two columns.
37+
if (! $value instanceof Name) {
38+
return [$key => $value];
39+
}
40+
41+
return [
42+
$this->firstName => $value->first,
43+
$this->lastName => $value->last,
44+
];
3445
}
3546
}

tests/Feature/NameCastTest.php

+13-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@
1212
->and($model->name->first)->toBe('John')
1313
->and($model->name->last)->toBe('Smith')
1414
->and($model->name->full)->toBe('John Smith')
15-
->and((string) $model->name)->toBe('John Smith');
15+
->and((string) $model->name)->toBe('John Smith')
16+
->and($model->getDirty())->toHaveKey('name')
17+
->and($model->getDirty()['name'])->toBe('John Smith');
1618
});
1719

1820
it('can be casted from first and last name on a model', function () {
@@ -30,3 +32,13 @@
3032
->and($model->custom_name->first)->toBe('John')
3133
->and($model->custom_name->last)->toBe('Smith');
3234
});
35+
36+
it('will not attempt to store a computed column to the database if it is accessed before saving the model', function () {
37+
$model = new Model(['given_name' => 'John', 'family_name' => 'Smith']);
38+
39+
$model->custom_name;
40+
41+
expect($model->getDirty())->not->toHaveKey('custom_name')
42+
->toHaveKey('given_name')
43+
->toHaveKey('family_name');
44+
});

0 commit comments

Comments
 (0)