Laravel - Relationships - Querying Relationship Existence

When retrieving model records, you may wish to limit your results based on the existence of a relationship. For example, imagine you want to retrieve all blog posts that have at least one comment. To do so, you may pass the name of the relationship to the has and orHas methods:

    
    use App\Models\Post;
    
    // Retrieve all posts that have at least one comment...
    $posts = Post::has('comments')->get();
	

You may also specify an operator and count value to further customize the query:

    
    // Retrieve all posts that have three or more comments...
    $posts = Post::has('comments', '>=', 3)->get();
	

Nested has statements may be constructed using "dot" notation. For example, you may retrieve all posts that have at least one comment that has at least one image:

    
    // Retrieve posts that have at least one comment with images...
    $posts = Post::has('comments.images')->get();
	

If you need even more power, you may use the whereHas and orWhereHas methods to define additional query constraints on your has queries, such as inspecting the content of a comment:

    
    use Illuminate\Database\Eloquent\Builder;
    
    // Retrieve posts with at least one comment containing words like code%...
    $posts = Post::whereHas('comments', function (Builder $query) {
        $query->where('content', 'like', 'code%');
    })->get();
    
    // Retrieve posts with at least ten comments containing words like code%...
    $posts = Post::whereHas('comments', function (Builder $query) {
        $query->where('content', 'like', 'code%');
    }, '>=', 10)->get();
	
Eloquent does not currently support querying for relationship existence across databases. The relationships must exist within the same database.