Skip to content

Commit 959fac8

Browse files
authored
Clear cast caches when discarding changes (#55992)
* test: reproduce issue * fix: clear cast caches when discarding changes * style: remove unnecessary variable
1 parent 7be06d1 commit 959fac8

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2155,6 +2155,9 @@ public function discardChanges()
21552155
{
21562156
[$this->attributes, $this->changes, $this->previous] = [$this->original, [], []];
21572157

2158+
$this->classCastCache = [];
2159+
$this->attributeCastCache = [];
2160+
21582161
return $this;
21592162
}
21602163

tests/Database/DatabaseEloquentModelTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3281,6 +3281,21 @@ public function testDiscardChanges()
32813281
$this->assertNull($user->getAttribute('name'));
32823282
}
32833283

3284+
public function testDiscardChangesWithCasts()
3285+
{
3286+
$model = new EloquentModelWithPrimitiveCasts();
3287+
3288+
$model->address_line_one = '123 Main Street';
3289+
3290+
$this->assertEquals('123 Main Street', $model->address->lineOne);
3291+
$this->assertEquals('123 MAIN STREET', $model->address_in_caps);
3292+
3293+
$model->discardChanges();
3294+
3295+
$this->assertNull($model->address->lineOne);
3296+
$this->assertNull($model->address_in_caps);
3297+
}
3298+
32843299
public function testHasAttribute()
32853300
{
32863301
$user = new EloquentModelStub([
@@ -3994,6 +4009,17 @@ public function thisIsAlsoFine(): Attribute
39944009
{
39954010
return Attribute::get(fn () => 'ok');
39964011
}
4012+
4013+
public function addressInCaps(): Attribute
4014+
{
4015+
return Attribute::get(
4016+
function () {
4017+
$value = $this->getAttributes()['address_line_one'] ?? null;
4018+
4019+
return is_string($value) ? strtoupper($value) : $value;
4020+
}
4021+
)->shouldCache();
4022+
}
39974023
}
39984024

39994025
enum CastableBackedEnum: string
@@ -4003,6 +4029,12 @@ enum CastableBackedEnum: string
40034029

40044030
class Address implements Castable
40054031
{
4032+
public function __construct(
4033+
public ?string $lineOne = null,
4034+
public ?string $lineTwo = null
4035+
) {
4036+
}
4037+
40064038
public static function castUsing(array $arguments): CastsAttributes
40074039
{
40084040
return new class implements CastsAttributes

0 commit comments

Comments
 (0)