-
Notifications
You must be signed in to change notification settings - Fork 11.5k
Description
Laravel Version
12.28.1
PHP Version
8.4.12
Database Driver & Version
Sqlite and postgres
Description
Doing queries in the constructor of a Global Scope that is applied to a model that is eager loaded will not apply the foreign key conditions for the relations loaded in scope for queries unrelated to the scope itself. You can see more details about this below
To note: I tested and it doesn't affect the result if the scope is added by an attribute or directly in booted
Steps To Reproduce
- Run
git clone https://github.com/wizzymore/laravel-bug-query
- Run the migrations ( ignore the dumps in the console )
- Open the application on the web
The dumps will show the query that was run and the models that were fetched.
The problem is that the query runs without the where condition
The second dump is the model that was fetched ( wrong )
The third dump is the model that should have been fetched
The source of the bug and dumps are in \App\Models\Scopes\TestScope.
TestScope is used on the Testing model, the bug appears when we run: Testing2::with('testing')->first()
Testing2 is a model that lazy loads testing ( which has the previously mentioned global scope ), when we lazy load the scoped model all queries ran inside the scope don't use foreign keys.
You can also access the /2
path which shows that if we don't eager load the scoped model and just construct the scope directly the query will work.