Laravel Eloquent “Has”, “With”, “WhereHas”, What do they mean?

Relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.

We will learn here, how to use "with", "has", and "wherehas" in laravel.  In examples below, we will show you how to use with, has and wherehas in laravel application.

"With" In laravel

with is for eager or fast loading, it means, along the main model, laravel will load relationship data you specify. This is helpful if you have a collection of models and you want to load a relation for all of them.


//Article has many comments



//Article has many comments and belongs to user

Article::with(['comments', 'users'])->get();

//comments and user is already loaded and no additional DB query is run

"Has" In laravel

Has is to filtering the selecting model based on a relationship, it acts very similar to where condition.



// only articles that have at least one comment are contained in the collection

"whereHas" In laravel

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


Article::whereHas('user', function ($query) {
                $query->where('status', 1);

// only active user's articles are returned

Hope it helps you...

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *