Using the with method to load Relationships with Eager Loading

- Andrés Cruz

En español

When we work with relationships in Eloquent, we often need to load all the relationships of a specific model or several, we are talking about having a main model and another or others that we relate using a foreign key and we want to load all this data in a single query, of course, using Eloquent and avoiding using Joins for ease of consultation; imagine that you have an online store with products, categories and tags. You want to get all the products along with their related categories and tags. This is where Laravel's eager loading comes into play, since, through the with method, we can specify the relationships from the main query, obtaining the data completely organized and without repeated records as would happen if we used JOINs.

Eager loading allows all necessary relationships to be loaded when performing the initial query. Instead of running a query for each model in the collection, Eloquent runs a single additional query to load all the relationships. This significantly improves the efficiency and speed of your application.

Suppose we have the following models: Product, Category and Tag. We want to get all the products along with their categories and tags:

$products = Product::with(['category', 'tags'])->get();

And now, we can access ALL of your relationships without needing additional queries:

foreach ($products as $product) {
    echo "Product: {$product->name}\n";
    echo "Category: {$product->category->name}\n";
    foreach ($product->tags as $tag) {
        echo "Tag: {$tag->name}\n";
    }
    echo "\n";
}

In this way, we can optimize the queries avoiding problems like N+1 in Laravel and with this, have efficient queries; In this way, we can very easily perform additional operations such as caching the data made in a single query by using optimized SQL queries.

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 3d 10:03!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!