Laravel Eloquent Relationships | Laravel Eager Loading Tutorial

 why we should use eager loading in laravel? I think we must have used eager loading with model eloquent in laravel. I will explain to you all the things why we have to use eager loading and eager loading with conditions, eager loading with the count, eager loading with constraints, eager loading with relationship, eager loading with where, eager loading with order by etc.

We will Optimize Eloquent Queries with Eager Loading in the laravel application. laravel introduce relationship like has one, has many, many to many, etc. It’s working great and we should use that relationship. it’s made easy to use and you don’t have to write a long query with join. so you can prevent writing long SQL queries. However, maybe some developers don’t know how the Laravel relationship is working and how many queries are fired on the backend with your database.

If you notice that you are getting data from the model and display it in your table for each loop. Other information regarding your relation data you are getting on under that loop. so it fires each time one single Eloquent Query on the backend and displays that records. it might be in the future it can be crash your server because of too many MySQL queries. Its solution laravel provides Eager Loading for Optimize this more queries.

You didn’t get me, not an issue. I will explain to you by example so you can understand how it works on the back end why we should use Eager Loading in the laravel application.

For Example, I have “posts” and “comments” tables and we know each other related data models. Post Model has many comments and Comment belongs to Post Model. So when you define your model then you will make it like as bellow both model

Post.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}

Comment.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
/**
* Get the post
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}

As you can see above moth eloquent model. we will define that as I write above and how you will get all posts and you also want to display all comments with that. then what you will do as like bellow

Display Post

$posts = Post::all();
foreach ($posts as $post) {
echo $post->name;
$comments = $post->comments;
/* You can write loop again  */
}

As you can see above. You will always do as I write above logic. it is not wrong. But you need to see how it works in the backend and how much query is being fired on the database. so let’s see below

Queries

-- Select the posts i.e. Post::all();
SELECT * FROM posts;
-- Foreach of the posts, another query to select the comments
-- i.e. $post->comments part of the loop
SELECT * FROM comments WHERE post_id = 1
SELECT * FROM comments WHERE post_id = 2
SELECT * FROM comments WHERE post_id = 3
SELECT * FROM comments WHERE post_id = 4
SELECT * FROM comments WHERE post_id = 5
.....

So now got how it works. each loop we execute another select query and get all comments. so whenever we are displaying 50 records then it’s firing 50 queries behind.

But we can prevent and instead of these more queries we can fire only one query and save database memory using Laravel Eager Loading. Now you can see below how to use it and how it works on the back-end.

Display Post with Eager Loading

$posts = Post::with('comments')->get();
foreach ($posts as $post) {
echo $post->name;
$comments = $post->comments;
/* You can write loop again  */
}

Now you can see below how works with database query

Queries with Eager Loading

-- Select the posts i.e. Post::all();
SELECT * FROM posts;
-- Just One time get all comments with for that posts
SELECT * FROM comments WHERE post_id IN (1, 2, 3, 4, 5, ...);

So basically, now you can understand how to work with Eager Loading and how you can use it. we can Eager Loading using with function. now I will suggest you use Eager Loading on your project so it might be not issued a letter on database memory.

Now I will give you more examples for Eager Loading in laravel. So you can use it flexibly. So let’s see below some examples

Eager Loading With Multiple Relationships

$posts = Post::with(['comments', 'author'])->get();

Eager Loading With Count

$posts = Post::withCount('comments')->get();
// comments_count

Eager Loading With Nested Relationship

$posts = Post::with(['comments', 'comments.user'])->get();

Eager Loading With Select Specific Columns

$posts = Post::with(['comments:is,body'])->get();

Eager Loading With Where Condition

$posts = Post::with(['comments' => function ($query) {
$query->where('type', 1);
}])->get();

Eager Loading With Order By

$posts = Post::with(['comments' => function ($query) {
$query->orderBy('created_at', 'desc');
}])->get();

No comments

Note: only a member of this blog may post a comment.