farahandev's avatar

What is the uses of With and Has ?

Can anyone tell me that what is the difference between With and Has in Laravel?

1 like
3 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

With

with() 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.

Example:

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
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. 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.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

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

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from this year are returned
shareeditflag

This answer has been taken from https://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean

8 likes
deepu07's avatar

with() is a preload the relationship(s) that you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them.

$authors= Author::with('books')->get();
foreach($authors as $author){
    $authors->books; // books are already loaded and no additional DB query is run
}

has() it acts very similarly to a normal WHERE condition. has() is used to filter the selecting model based on a relationship.

$authors= Author::has('books')->get();
// only authors that have at least one book is contained in the collection
`
3 likes

Please or to participate in this conversation.