Laravel Relationship Eager Loading Example

By Hardik Savani April 16, 2024 Category : Laravel

why we should use eager loading in laravel?, i think we must have to use eager loading with model eloquent in laravel 5.8. i will explain you all the thing why we have to use eager loading and eager loading with conditions, eager loading with 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 laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 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 make easy to use and you don't have to write long query with join. so you can prevent to write long sql query. However, may be some developer don't know how Laravel relationship is working and how many queries are fire on backend with your database.

If you notice that you are getting data from model and display in your table with for each loop. Other information regarding your relation data you are getting on under that loop. so it fire each time one single Eloquent Query on backend and display that records. it might be in future it can be crash your server because of too much mysql query. It's solution laravel provide Eager Loading for Optimize this more queries.

You didn't get me, not a issue. i will explain you by example so you can understand how it works on back end why we should use Eager Loading in laravel 5 application.

For Example i have "posts" and "comments" tables and we know each other related data model. 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 backend and how much query being fire on database. so let's see belloe:

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 it how it works. each loop we execute another select query and getting all comments. so when ever we are displaying 50 records then it's fire 50 query behind.

But we can prevent and instead of this more queries we can fire only one query and save database memory using Laravel Eager Loading. Now you can see bellow how to use it and how it works on 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 bellow 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 to use Eager Loading on your project so it might be not issue letter on database memory.

Now i will give you more example for Eager Loading in laravel. So you can use with flexible way. So let's see bellow 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();

You can use more.

I hope you understand eager loading in laravel and you can use in your application.

I hope it can help you...

Tags :
Shares