How to use whereHas to retrieve rows based on existence of relationship

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();

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent