Skip to content

Commit

Permalink
fix virtual attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Jan 7, 2022
1 parent 310c270 commit 29a6692
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -1637,7 +1637,13 @@ protected function mergeAttributesFromClassCasts()
protected function mergeAttributesFromAttributeCasts()
{
foreach ($this->attributeCastCache as $key => $value) {
$callback = $this->{Str::camel($key)}()->set ?: function ($value) use ($key) {
$attribute = $this->{Str::camel($key)}();

if ($attribute->get && ! $attribute->set) {
continue;
}

$callback = $attribute->set ?: function ($value) use ($key) {
$this->attributes[$key] = $value;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,17 @@ public function testSettingRawAttributesClearsTheCastCache()

$this->assertSame('117 Spencer St.', $model->address->lineOne);
}

public function testCastsThatOnlyHaveGetterDoNotPeristAnythingToModelOnSave()
{
$model = new TestEloquentModelWithAttributeCast;

$model->virtual;

$model->getAttributes();

$this->assertTrue(empty($model->getDirty()));
}
}

class TestEloquentModelWithAttributeCast extends Model
Expand Down Expand Up @@ -253,6 +264,15 @@ public function password(): Attribute
return hash('sha256', $value);
});
}

public function virtual(): Attribute
{
return new Attribute(
function () {
return collect();
}
);
}
}

class AttributeCastAddress
Expand Down

1 comment on commit 29a6692

@koenvu
Copy link

@koenvu koenvu commented on 29a6692 Jan 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a typo in the test name testCastsThatOnlyHaveGetterDoNotPeristAnythingToModelOnSave "Perist" 😊

Please sign in to comment.