-
Notifications
You must be signed in to change notification settings - Fork 11k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Eloquent custom class cast cache problem #33311
Comments
Share your cast class. |
class MyEnum implements Castable
{
public const VALUE = 1;
public const OTHER_VALUE = 2;
public $value;
public function __construct($value = null)
{
$this->value = $value;
}
public static function castUsing()
{
return new MyEnumCast(static::class);
}
}
class MyEnumCast implements CastsAttributes
{
protected $enumClass;
public function __construct(string $enumClass)
{
$this->enumClass = $enumClass;
}
public function get($model, string $key, $value, array $attributes)
{
if ($value === null) {
return $value;
}
if ($value instanceof MyEnum) {
return $value;
}
return new $this->enumClass($value);
}
public function set($model, string $key, $value, array $attributes)
{
$value = $this->get($model, $key, $value, $attributes);
return [$key => $value->value ?? null];
}
} |
Fixed by: b20125d Can you try this patch in your own application? |
Thanks for the quick feedback. $user = new MyUser([
'prop' => MyEnum::VALUE,
]);
$user->syncOriginal();
$user->prop = MyEnum::OTHER_VALUE;
dump($user->prop, $user->getOriginal(), $user->prop);
/*
MyEnum {#1443
+value: 2
}
array:1 [
"prop" => MyEnum {#1443
+value: 2
}
]
MyEnum {#1443
+value: 2
}
*/ |
I will make a slight change for this; however, it's important to note that if you pull a record from the database and hit |
OK thanks. |
Will be fixed in next patch release. |
Description:
Eloquent is caching the result of custom class cast calls. The cache key is the attribute name.
There is only one cache that is used for both original and dirty attributes.
As a result:
getOriginal
orgetAttribute
will always be returned until the cache is reset,mergeAttributesFromClassCasts
is called fromHasAttributes::getAttributes
.Steps To Reproduce:
syncOriginal
getOriginal
:$classCastCache
is initialized with the original valueHasAttributes::mergeAttributesFromClassCasts
inHasAttributes::getAttributes
Possible Fixes
We might create two caches: one for original values and one for changes.
We could also not use the cache with
getOriginal
.I did the following in my BaseModel:
The text was updated successfully, but these errors were encountered: