Eloquent Relationships in Laravel: “Has”, “With” and “WhereHas” Methods

- Andrés Cruz

En español

In Laravel, the model layer with Eloquent is one of the richest MVC layers that Laravel includes and with the most options, and it is not superfluous, since it is the data layer, which connects to the database. data to manage it; there are many methods available in Eloquent, but, we are going to know 3 that can be confused with “Has”, “With” and “WhereHas”.

1. "Has": Filtering models based on relationships

The has() method is used to filter the selected models based on a relationship. It works similar to a normal WHERE condition but with a relationship.

If you use has('relation'), it means that you only want to get the models that have at least one related model in this relationship.

For example, let's consider a blog system with two tables: “posts” and “comments”. If we want to get all the users who have at least one comment, we can do it as follows:

$users = User::has('comments')->get();
// Only users who have at least one comment in the collection will be included

In short, it is a kind of conditional in which users who have at least one comment are obtained; In this example, comments are a list of users.

2. "With": Loading relationships efficiently (eager loading)

The with() method is used to load relationships along with the main relationship. Previously we saw the N+1 problem in Laravel that is solved by the with method.

Basically, along with the main model, Laravel will load the relationships you specify. This is especially useful when you have a collection of models and want to load a relationship for all of them.

$users = User::with('posts')->get();
foreach ($users as $user) {
    // Posts are already loaded and no additional query is executed
    $user->posts;
}

3. "WhereHas": Filtering based on relationships with additional conditions

The whereHas() method works similarly to has(), but allows you to specify additional filters for the related model. You can add custom conditions to check in the related model.

For example, if we want to get all the users who have posts created after a specific date, we can do it like this:

$users = User::whereHas('posts', function ($query) {
    $query->where('created_at', '>=', '2021-01-01 00:00:00');
})->get();
// Only users who have posts from 2021 onwards will be included
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 4d 09:01!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!