-
Notifications
You must be signed in to change notification settings - Fork 11.5k
Description
Laravel Version
12.0
PHP Version
8.4
Database Driver & Version
MariaDB
Description
If you have relations and subrelations all set up, you can do something like this:
$user->load("friends.cars", function($query) { $query->where("make", "Ford"); } );
Now, when you ask for this user's friends' cars, only Fords will show up in the list. This works great!
However, you might also want to load another relation right after it, like this.
$user->load("friends.cars", function($query) { $query->where("make", "Ford"); } );
$user->load("friends.clothes", function($query) { $query->where("type", "hat"); } );
If, after running this code, you ask for this user's friends' cars, you will unexpectedly see BMWs and Chevys in the list. It looks like that second "load" statement is deleting the filter from the first "load" statement.
However, if you put both of these statements together into an array, like the following code, it will work as expected.
$user->load([
"friends.cars" => function($query) { $query->where("make", "Ford"); },
"friends.clothes" => function($query) { $query->where("type", "hat"); }
]);
Now the user's friends all drive only Fords again.
It took me a long time of hunting to discover this. I can say for myself it was very non-intuitive. Surely this would be considered a bug, wouldn't it?
Steps To Reproduce
You'll need a pile of models, and more importantly relations set up that return "HasMany".
The first model needs a relation to the second model, and that model needs relations to two others.
After loading the model's relations, including filter, as described above, something like this might detect it:
dump($user->friends->first()->cars->count());