Difference between Eager Loading and Lazy Loading

Laravel
August 13, 20221 minuteuserVishal Ribdiya
Difference between Eager Loading and Lazy Loading

We often listen to the words "Eager Loading" & "Lazy Loading" in Laravel. but maybe some of how still don't know what that actually stands for.

What Lazy Loading means?

I worked with many projects that is developed by some other developers and the common problems in code I found us Lazy Loading queries everywhere.

To understand it more easily let's take one simple example.

Let's say There is Post model and Comments Model.

So basically post->hasMany('comments')

So let's say we are fetching 10 posts and now we want the comments of each post. what we will do is :

$post->comments()->get() (LAZY LOADING)

Lazy loading cause N+1 queries issues as every time we are fetching comments of each post and it will block the execution too for while as its queries from the DB.

What Eager Loading means?

Eager loading is very useful when we are working with large-scale projects. it saves lot's of execution time and even DB queries too :)

Let's take the above example to understand the Eager loading.

$posts = Post::with('comments')->get()

$post->comments (EAGER LOADING)

here when we retrieve the posts at that time we are fetching its comments too on the same query. so when we do $post->comments it will not again do query into DB or not even block execution as the comments are already there in model instance.

So this is how Eager loading saves your time and also prevents N+1 Query.

Hope that helps.