framework icon indicating copy to clipboard operation
framework copied to clipboard

Model relations don't work in global scopes of eager loaded models

Open wizzymore opened this issue 3 months ago • 9 comments

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

  1. Run git clone https://github.com/wizzymore/laravel-bug-query
  2. Run the migrations ( ignore the dumps in the console )
  3. 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.

wizzymore avatar Sep 06 '25 01:09 wizzymore