[10.x] Failing test/bug report in HasManyThrough
updateOrCreate()
since Laravel 10.21
#48529
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.
Last week, I had a weird bug in an application, where suddenly records from different users become visible to each other. The bug seemed to be related to a certain
updateOrCreate()
method. Suddenly, old records from one year ago were being updated with recent data from other users.After much digging, I found that there seems to be a bug introduced in Laravel 10.21.0. Consider the following code:
The error happens in the following code:
Say that User A has a booking with an ID of
1234
. ThisupdateOrCreate()
statement would just randomly find any leg with an ID of1234
and update that random leg with the data from the secondupdateOrCreate()
parameter. Said again, the error is that this code would retrieve legs by ID instead of the actual conditions specified , and for the leg ID it takes the booking ID. So it could update a leg of User B with data from User A.This is very dangerous bug in an application. I've been able to reproduce the case in a failing test, which you find attached to this PR. If you run this test on Laravel 10.20.0, the test will pass. If you run this on Laravel 10.21.0 or later, it will fail (like it currently does).
The code where the bug was introduced is #48192 in the
HasManyThrough.php
file, because if I revert the code in theupdateOrCreate()
method there, the code works as expected. However, the code in that file doesn't look too strange, so probably it's an underlying bug in hydrating the model. Please see the test for a better explanation.I checked the queries that are being run and the full flow from a
->where($conditions)->first()
until executing the statement, but I do not see anything wrong there:However, even after double-checking multiple times, the test keeps passing on 10.20.0 and keeps failing on 10.21.0, so the bug must be somewhere in these 53 files.