whereHas() method is used to add further query constraints on top of has() method.
Suppose, there is user hasMany relationship with posts, following snippet describes two scenarios of whereHas.
First one retrieves users based on relationship with posts which has at least one row that has "how to" in the title.
Second one, retrieves posts that has given number of comments inside comment text "how to" and in our example given number is 2
use Illuminate\Database\Eloquent\Builder; // 1. Retrieve users with at least one post containing words like how to%... $users = User::whereHas('posts', function (Builder $query) { $query->where('title', 'like', 'how to%'); })->get(); // 2. Retrieve posts with at least 2 comments containing words like how to%... $posts = Post::whereHas('comments', function (Builder $query) { $query->where('title', 'like', 'how to%'); }, '=', 2)->get();