Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? | Laravel Point

 


"Has" in Laravel Eloquent refers to a relationship type "Has One" or "Has Many", which represents a one-to-one or one-to-many relationship between two models respectively.

"With" is a method used in Eloquent to eager load relationships along with the main query, reducing the number of database queries needed.

"WhereHas" is a method used in Eloquent to add a conditional clause to the relationship query, allowing you to retrieve only the models that have a relationship that satisfies certain conditions.

For example, if you have a model "User" and a model "Address", where a user has one address, you can use "Has" to define this relationship, "With" to eager load the related address when retrieving users, and "WhereHas" to only retrieve users who have a specific type of address.

Here's an example to illustrate the usage of "Has", "With", and "WhereHas" in Laravel Eloquent:

Consider a scenario where you have two models - User and Post. A user can have many posts. Here's how you can define the relationship using "Has":

       class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

 

Now, you can use "With" to eager load the related posts when retrieving users:

$users = User::with('posts')->get();

And you can use "WhereHas" to only retrieve users who have at least one post:

$users = User::whereHas('posts')->get();

or only retrieve users who have a specific type of post:

  $users = User::whereHas('posts', function ($query) {
    $query->where('type', 'news');
})->get();

Note that, "With" and "WhereHas" are used to customize the relationship query and retrieve only the data that you need.

Previous Post Next Post

Contact Form