Skip to content

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

@wizzymore

Description

@wizzymore

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions