Skip to content

Commit 29a6692

Browse files
committed
fix virtual attributes
1 parent 310c270 commit 29a6692

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1637,7 +1637,13 @@ protected function mergeAttributesFromClassCasts()
16371637
protected function mergeAttributesFromAttributeCasts()
16381638
{
16391639
foreach ($this->attributeCastCache as $key => $value) {
1640-
$callback = $this->{Str::camel($key)}()->set ?: function ($value) use ($key) {
1640+
$attribute = $this->{Str::camel($key)}();
1641+
1642+
if ($attribute->get && ! $attribute->set) {
1643+
continue;
1644+
}
1645+
1646+
$callback = $attribute->set ?: function ($value) use ($key) {
16411647
$this->attributes[$key] = $value;
16421648
};
16431649

tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,17 @@ public function testSettingRawAttributesClearsTheCastCache()
177177

178178
$this->assertSame('117 Spencer St.', $model->address->lineOne);
179179
}
180+
181+
public function testCastsThatOnlyHaveGetterDoNotPeristAnythingToModelOnSave()
182+
{
183+
$model = new TestEloquentModelWithAttributeCast;
184+
185+
$model->virtual;
186+
187+
$model->getAttributes();
188+
189+
$this->assertTrue(empty($model->getDirty()));
190+
}
180191
}
181192

182193
class TestEloquentModelWithAttributeCast extends Model
@@ -253,6 +264,15 @@ public function password(): Attribute
253264
return hash('sha256', $value);
254265
});
255266
}
267+
268+
public function virtual(): Attribute
269+
{
270+
return new Attribute(
271+
function () {
272+
return collect();
273+
}
274+
);
275+
}
256276
}
257277

258278
class AttributeCastAddress

0 commit comments

Comments
 (0)