Skip to content
Advertisement

How to apply Eloquent where() to child in hasMany() relationship

I want to get the results of this very simple, common SELECT statement:

JavaScript

For the non-SQL fluent, this returns all of the columns for all parent and child rows where the child column named column contains the value 1.

Using the Laravel models below, what’s the correct Eloquent way to do this?

JavaScript

Advertisement

Answer

You were close with your last attempt; your callback filters the Parent instances returned, but not the attached Child instances. Try something like this:

JavaScript

The callback has to be repeated for both the whereHas and with methods…

  • TheParent::with('child') returns all parents with all children
  • TheParent::with(['child' => 'some condition']) returns all parents with some children
  • TheParent::whereHas('child', 'some condition') returns some parents with all children
  • TheParent::whereHas('child', 'some condition')->with(['child' => 'some condition']) returns some parents with some children.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement