Laravel Eager Loading Tutorial

Originally published by Hardik Savani at https://itsolutionstuff.com

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 5.8 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-&gt;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 bellow:

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-&gt;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.

Laravel Eager Loading with Count Relationship Example

Eager Loading is a concept of laravel relationship and it is a best. But when you are working with model relationship with eager loading then you require to get count number of records for relation model. At that we can use withcount() for eager loading count in Laravel 5.8.

Whenever you require to count rows of relation model then we will use withcount(). So that can help us. you can see bellow example. i will count number of comments for each posts. you can see bellow example.

Let’s see bellow example. So might be it can help you.

Simple Count Example:

$posts = Post::withCount(‘comments’)->get();

// comments_count

Multiple Counts Example:

$posts = Post::withCount([
‘comments’,
‘tags’
])->get();

// comments_count
// tags_count

Count with Condition Example:

$posts = Post::withCount([
‘comments’,
‘comments as active_comments’ => function (Builder $query) {
$query->where(‘approved’, 1);
}
])->get();

// comments_count
// active_comments

Laravel Eager Loading with Condition Relationship Example

In this post, we will lean how to write conditional statement with eager loading in Laravel. We can write where, wherehas condition with laravel eager loading. I will give you simple example of where condition eager laravel relationship model.

Eager Loading is a concept of Laravel relationship and it is a best. But we some time taking relation model data at that time we need to add condition like active data or only enabled data etc as per our logic. so we can do it in Laravel eager loading.

You can see following example will easily understandable. Let’s see bellow example. So might be it can help you.

Simple Condition Example:

$posts = Post::with([
‘comments as active_comments’ => function (Builder $query) {
$query->where(‘approved’, 1);
}
])->get();

Nested Condition Example:

$posts = Post::with([
‘comments.user’ => function (Builder $query) {
$query->where(‘active’, 1);
}
])->get();

Laravel Eager Loading with Selected Columns Example

In this post, we will lean how to select specific columns with eager loading relation in Laravel. we can get specific columns using with() function in laravel eloquent. I will give you simple example of Laravel eloquent select specific columns with eager loading.

Eager Loading is a part of Laravel relationship and it is a best. But we some time we just need to get specific columns from relation model. at that time we can do it with select statement and also define with colon.

You can see following example will easily understandable. Let’s see bellow example. So might be it can help you.

Get All Fields Example:

$posts = Post::with(‘comments’)->get();

Simple Select Example:

$posts = Post::with(‘comments:id,body’)->get();

Select with statement Example:

$posts = Post::with([‘comments’ => function($query) {
return $query->select([‘id’, ‘body’]);
}])->get();

I hope it can help you…

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More about

PHP with Laravel for beginners - Become a Master in Laravel

Projects in Laravel: Learn Laravel Building 10 Projects

Laravel for RESTful: Build Your RESTful API with Laravel

Fullstack Web Development With Laravel and Vue.js

Laravel 5.8 Ajax CRUD tutorial using Datatable JS

Laravel 5.8 Tutorial from Scratch for Beginners

Build RESTful API In Laravel 5.8 Example

Login with Google in Laravel 5.8 App using Socialite Package

Laravel PHP Framework Tutorial - Full Course for Beginners (2019)



#laravel #php #web-development

Laravel Eager Loading Tutorial
89.80 GEEK