Skip to content

Commit b20125d

Browse files
committed
address original class cast issue
1 parent e6a660c commit b20125d

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

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

+6
Original file line numberDiff line numberDiff line change
@@ -1185,6 +1185,12 @@ public function setRawAttributes(array $attributes, $sync = false)
11851185
*/
11861186
public function getOriginal($key = null, $default = null)
11871187
{
1188+
if ($key && $this->isClassCastable($key) && $this->isDirty()) {
1189+
return (new static)->setRawAttributes(
1190+
$this->original, $sync = true
1191+
)->getOriginal($key, $default);
1192+
}
1193+
11881194
if ($key) {
11891195
return $this->transformModelValue(
11901196
$key, Arr::get($this->original, $key, $default)

tests/Integration/Database/DatabaseEloquentModelCustomCastingTest.php

+38
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,33 @@ public function testBasicCustomCasting()
9393
$this->assertTrue(is_string($model->toArray()['birthday_at']));
9494
}
9595

96+
public function testGetOriginalWithCastValueObjects()
97+
{
98+
$model = new TestEloquentModelWithCustomCast([
99+
'address' => new Address('110 Kingsbrook St.', 'My Childhood House')
100+
]);
101+
102+
$model->syncOriginal();
103+
104+
$model->address = new Address('117 Spencer St.', 'Another house.');
105+
106+
$this->assertEquals('110 Kingsbrook St.', $model->getOriginal('address')->lineOne);
107+
$this->assertEquals('117 Spencer St.', $model->address->lineOne);
108+
109+
110+
$model = new TestEloquentModelWithCustomCast([
111+
'address' => new Address('110 Kingsbrook St.', 'My Childhood House')
112+
]);
113+
114+
$model->syncOriginal();
115+
116+
$model->address = null;
117+
118+
$this->assertNull($model->address);
119+
$this->assertInstanceOf(Address::class, $model->getOriginal('address'));
120+
$this->assertNull($model->address);
121+
}
122+
96123
public function testOneWayCasting()
97124
{
98125
// CastsInboundAttributes is used for casting that is unidirectional... only use case I can think of is one-way hashing...
@@ -213,11 +240,22 @@ class AddressCaster implements CastsAttributes
213240
{
214241
public function get($model, $key, $value, $attributes)
215242
{
243+
if (is_null($attributes['address_line_one'])) {
244+
return null;
245+
}
246+
216247
return new Address($attributes['address_line_one'], $attributes['address_line_two']);
217248
}
218249

219250
public function set($model, $key, $value, $attributes)
220251
{
252+
if (is_null($value)) {
253+
return [
254+
'address_line_one' => null,
255+
'address_line_two' => null,
256+
];
257+
}
258+
221259
return ['address_line_one' => $value->lineOne, 'address_line_two' => $value->lineTwo];
222260
}
223261
}

0 commit comments

Comments
 (0)