[7.x] Cast primary key to string when $keyType is string #33930
Merged
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.
Problem
Given a model with a string primary key:
and then running this on the model:
I expect a
null
result, but in fact I get the first row in the table.Looking at the underlying query, sure enough it runs
select * from payment_providers where id = 0
; MySQL seems to have a quirk where it will return all rows when comparing a string to a0
integer.MySQL aside, I think Laravel should take care of casting the primary key according to
$keyType
to prevent unexpected results.Solution
This PR checks the primary key type, and casts to a string when required in
whereKey()
andwhereNotKey()
.Caveats
This query will return a collection of all rows in the table. I wasn't sure how to deal with an array of IDs, so I dealt with the singular lookup only.