Skip to content

Commit

Permalink
unset cached cast attribute (#53583)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamthehutt authored Nov 20, 2024
1 parent aa686b6 commit e7bdd64
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -2317,7 +2317,7 @@ public function offsetSet($offset, $value): void
*/
public function offsetUnset($offset): void
{
unset($this->attributes[$offset], $this->relations[$offset]);
unset($this->attributes[$offset], $this->relations[$offset], $this->attributeCastCache[$offset]);
}

/**
Expand Down
30 changes: 30 additions & 0 deletions tests/Database/DatabaseConcernsHasAttributesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Concerns\HasAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Mockery as m;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -49,6 +50,17 @@ public function testCastingEmptyStringToArrayDoesNotError()

$this->assertTrue(json_last_error() === JSON_ERROR_NONE);
}

public function testUnsettingCachedAttribute()
{
$instance = new HasCacheableAttributeWithAccessor();
$this->assertEquals('foo', $instance->getAttribute('cacheableProperty'));
$this->assertTrue($instance->cachedAttributeIsset('cacheableProperty'));

unset($instance->cacheableProperty);

$this->assertFalse($instance->cachedAttributeIsset('cacheableProperty'));
}
}

class HasAttributesWithoutConstructor
Expand Down Expand Up @@ -88,3 +100,21 @@ public function usesTimestamps(): bool
return false;
}
}

/**
* @property string $cacheableProperty
*/
class HasCacheableAttributeWithAccessor extends Model
{
public function cacheableProperty(): Attribute
{
return Attribute::make(
get: fn () => 'foo'
)->shouldCache();
}

public function cachedAttributeIsset($attribute): bool
{
return isset($this->attributeCastCache[$attribute]);
}
}

0 comments on commit e7bdd64

Please sign in to comment.