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.

Example


//Article has many comments

Article::with('comments')->get();

OR

//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.

Example


Article::has('comments')->get();

// 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.

Example


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

// 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 *
Phone