Replies: 2 comments
-
First, out of curiosity, aren't I couldn't find any reference to it on the whole https://github.com/search?q=org%3Alaravel%20whereState&type=code other than this very issue, and some references on 2 PRs regarding code samples As you reference them like a built-in feature, you got me curious about this. Second:
Yes, that is the way to go. If you use It always worked this way. Maybe we could handle those as we do with Model scopes (automatically wrap them into a closure), but in contrast with scopes where you already pass the whole |
Beta Was this translation helpful? Give feedback.
-
@rodrigopedra This is not a bug but a know feature / bad usage that was previously discussed. It could be a feature request at most. |
Beta Was this translation helpful? Give feedback.
-
Laravel Version
12.10.2
PHP Version
8.4.3
Database Driver & Version
No response
Description
We discovered a logic issue when using orWhereState directly on a relationship query. For example:
Although this seems correct at first glance, it results in incorrect SQL logic.
This means that some posts not belonging to the given user may be included, because the OR applies globally.
✅ Correct version
To ensure the condition applies only to the user's posts, the status logic must be wrapped in a closure:
When using orWhere* (including orWhereState) in combination with relationship constraints (e.g. $user->posts()), always wrap those conditions in a where(function ($q) { ... }) block. This avoids incorrect global application of OR clauses and ensures consistent results.
Steps To Reproduce
Create a simple model relationship:
Use Laravel Model States (e.g. Spatie model states) and define two states for status:
Seed the database with sample data:
Run the problematic query:
Expected result: Only posts belonging to $userA and having status of either Published or Archived.
Actual result: You will get the Archived post that belongs to $userB, which should not be included.
Beta Was this translation helpful? Give feedback.
All reactions