Addition of a JSON Cast Type #42424
Unanswered
DeanWhitehouse
asked this question in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hey Folks,
I came across an interesting challenge today whilst using a JSON field in the database, let me explain further. Details of how I discovered this issue are on Larachat https://larachat.slack.com/archives/C039F76DN/p1652876860353939
I believe that changing the existing
object
comparison within theobject
cast will be too much of a breaking change to existing applications, so I believe we should add a specific JSON cast where we can compare JSON changes in a specific way.Issue 1
Object comparison within Laravel is currently inaccurate for anyone wishing to utilise
null
values, this is outlined by PHP themselves (kinda) in their docs about property value comparison https://www.php.net/manual/en/language.oop5.object-comparison.php.We are currently utilising the
==
comparison within theoriginalIsEquivalent
method in theHasAttributes
trait (/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
).This means that when you change a property value from
null
tofalse
, as far as this method is concerned, nothing has changed and therefore it doesn't attempt to commit anything to the database (or mark the model as dirty).Proposed Solution
Implement a reflection based "deep" comparison of the objects to account for the
null
/false
issue, someone has suggested an approach here https://www.php.net/manual/en/language.oop5.object-comparison.php#121105Issue 2
JSON changes are currently assessed by their cast, this seems inefficient compared to comparing two serialized JSON strings.
Proposed Solution
Add a
JSON
cast type https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting, this would cast to object by default following the standard of https://www.php.net/manual/en/function.json-decode.php. For comparisons withoriginalIsEquivalent
we would then use a string comparison to determine any changes.Beta Was this translation helpful? Give feedback.
All reactions