[9.x] Fix inconsistent results of firstOrNew() when using withCasts()#41257
Merged
taylorotwell merged 3 commits intoFeb 28, 2022
Merged
Conversation
Attia-Ahmed
force-pushed
the
fix_inconsistent_results_of_firstOrNew
branch
from
February 25, 2022 22:05
2a85586 to
a26bde4
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The issue is when using
withCaststo override model casts, leads to inconsistent results when usingfirstOrNewmethod or any similar method depends onModel::newInstance()such asfirstOrCreate(),updateOrCreate. the results are differ depends on whether the element exists on DB or not, as one result of Model$castsand other formwithCasts().For example:
If we have a Model with
$casts = ['time' => 'datetime'];and by running these queries:
both queries will leads to different entries on database as under the hood
wheremethod is looking fortime = 07:30and fail to find one, thennewInstance()method will create new instance withdatetimecast, so the next query will fail to findtime = 07:30and this behavior will remain for every use offirstOrCreateunless there is an existent entire in DB matches the attribute.So developer won't be able to depend on
firstOrCreate,updateOrCreateorfirstOrNewto have consistent and unique data in the database in such cases.I have started with failing tests to prove the issue, and end up with solving it by modifing
newInstancemethod to fill model attributes aftermergeCasts.