-
Notifications
You must be signed in to change notification settings - Fork 11.6k
[12.x] Fixes incorrectly serializing virtual properties #57199
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
[12.x] Fixes incorrectly serializing virtual properties #57199
Conversation
Can this have a test? |
There. I fixed it. Took some magic because it's PHP 8.4 code running on previous versions, so I had to add a reusable rule to the |
Is there a way to do this without the array cast? |
public function __serialize(): array
{
$this->mergeAttributesFromCachedCasts();
$props = get_mangled_object_vars($this);
// Remove the attributes that are should be unserialized with default values
unset(
$props["\0*\0classCastCache"],
$props["\0*\0attributeCastCache"],
$props["\0*\0relationAutoloadCallback"],
$props["\0*\0relationAutoloadContext"],
);
return $props;
} It is only suggestion.
get_mangled_object_vars($obj) is equivalent of (array)$obj and ignores virtual and unitialized props. |
Using I modified the PR with your suggestion for removing the cache keys from the props instead of the instance. Another alternative is to use |
You no need to clean them if you will use __serialize instead __sleep as in the example |
Dunno if I can just use serialize. Theoretically it will be just fine, so I’ll update that then. I hope there is no dev using a custom serialization.Once it’s accepted I’m gonna back port it to 11.x.
|
Can someone te run this again. Seems that docker failed. |
May revisit this for Laravel 13.x. Will note it on my todo list. |
The problem
When adding virtual properties to models, serializing them (like when happens when these are stored in a cache store) will return an error.
For example, consider the following model:
When trying to serialize it with
serialize($model)
, like it happens when using the application cache, it will return an error like this:This may be cumbersome if someone is adding virtual properties to a model for whatever reason, like live calculation or else, because the patchwork is to alter the
__sleep()
method on each offending class, or use alternative abstract Model and hope nothing breaks in between.The Fix
The fix uses a simple
(array)
cast to the model instance to get the non-virtual keys, and anarray_map
to clean the name of each key returned.