Laravel WhereHas Eloquent Example - Yudhy Network

Share on:

Yudhy Network - Laravel whereHas eloquent method. Here, you will how to use laravel eloquent whereHas() with condition to building a query in laravel apps.

Laravel whereHas() eloquent method. In this tutorial, you will learn about laravel eloquent whereHas() with example. But first of all, you need to know about has() and with() eloquent method.

Sometime, Laravel eloquent haswith and whereHas methods are very confusing for programmers. Now let’s take look at examples for better understanding of this methods.

First of all you know about the laravel with() method,:


Laravel with() eloquent method is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.


User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run


Laravel eloquent has() method is used to filter the selecting model based on the selected relationship. It works similarly to where method for relations.

If you just use has(‘relation’) that means you only want to get the models that have at least one related model in this relation.


User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
Recommended:- Laravel whereExists and where Not Exists Query Example


Laravel eloquent whereHas() method works basically the same as has() but it just allows you to specify additional filters for the related model to check.


User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2020-01-01 00:00:00');
// only users that have posts from 2020 on forward are returned
Recommended:- Laravel Multiple Where Conditions Example
Recommended:- Laravel Eloquent whereRaw Query Example
Recommended:- Laravel – where In Eloquent Query Example
Recommended:- Laravel whereIn, where Not In With SubQuery Example
Recommended:- Laravel where Like Query Example
Recommended:- Laravel where Between Dates Eloquent Query
Recommended:- Laravel where Not In Eloquent Query Example
Recommended:- Laravel where Not Between Query Example
Recommended:- Laravel Where Null and Where Not Null Query
Recommended:- Laravel Group by Example
Recommended:- Laravel Order by Example
Recommended:- Laravel InsertOrIgnore Example

Please ask in the comments!

Suport : Cotekno.Com

comments powered by Disqus