Custom cast class overrides the related column #51923
Replies: 6 comments
-
Hi @foremtehan, The framework is functioning as expected here. The issue arises from the incompatibility between your When you access your custom cast using However, when you call For normal serialization Laravel uses PHP's A part of this method call involves using the custom cast setter to prepare your value. The resulting code essentially does this: return json_encode(new TestCast()); Since you haven't specified how PHP should serialize your class, perhaps by implementing When creating a custom cast, ensure that the output value from your I hope this clarifies things. If you have any follow-up questions, I’d be happy to help. |
Beta Was this translation helpful? Give feedback.
-
I didn't assign a value to the name column, so why would it trigger the set method on the castable class? Additionally, note that I tested it, and the framework never invoked the set method when using |
Beta Was this translation helpful? Give feedback.
-
It doesn't trigger the Then later on when it needs to Try it yourself. Access it with |
Beta Was this translation helpful? Give feedback.
-
Overall, this is unwanted behavior. Just imagine using $user->name in your app, and then calling save() somewhere in your codebase afterward. Your data will be lost. I’ll let the maintainers decide whether to close this issue, but I have demonstrated the problem. |
Beta Was this translation helpful? Give feedback.
-
You control how the The comment for the set method even tells you this..
|
Beta Was this translation helpful? Give feedback.
-
Is there a real world example of this? because in the end, get should cast to the object value you want it in, and set should use an object value to convert back to a value that can be stored in the database, which in your case isn't happening at all. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Laravel Version
v11.1.1
PHP Version
8.3
Database Driver & Version
sqlite, pgsql, mysql
Description
When you return a new custom class in castable interface's get method, It overrides the related volumn whenever you use the column on the model object
Steps To Reproduce
create a class:
create a custom castable class and return the above class inside a get method:
Apply this to user's name column (you can add new column to the table doesn't matter)
User.php
I ran these in fresh laravel app:
As you can see, when you use
->name
, the name column becomes{}
for no reason! It doesn't matter if the column type is json, string, etc. it is always overridden by the castable class.This is really dangerous since this can flush data when you try to save the model after using the attribute.
Beta Was this translation helpful? Give feedback.
All reactions