Laravel WhereHas Eloquent Example

Laravel WhereHas Eloquent Example

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

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


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


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

Here is an example of WhereHas with Relationship Condition in laravel:

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


That’s it; you have learned how to use whereHas with relationship, has() and with() in laravel.

Recommended Tutorials


Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *