October 26th, 2023

Differences between lazy loading and eager loading

Differences between lazy loading and eager loading

In Laravel, eager loading and lazy loading are two different techniques for retrieving related data when working with Eloquent models. They are used to optimize the performance of your application by reducing the number of database queries needed to fetch related data.

Lazy Loading

Lazy loading, also known as "on-demand loading," is the default behavior in Eloquent. When you access a related model or collection, Eloquent will only retrieve the data from the database at the moment you request it. This means that for each access to a related record, a separate database query is executed.

Lazy loading is more straightforward to use because you don't have to explicitly specify which related data to load in advance. However, it can lead to performance issues, especially when accessing related data for multiple records in a loop, resulting in the N+1 query problem.

Example of lazy loading in Laravel:

1$posts = Post::all();
2foreach ($posts as $post) {
3 $comments = $post->comments; // A separate query for each post to load comments
4}

In this example, a new query is executed for each post to load its associated comments, potentially leading to performance issues when dealing with a large number of records.

Eager loading

Eager loading is the process of fetching related data along with the main model's data in a single query. This is accomplished using the with() method in Eloquent. Eager loading is useful when you know that you will need the related data for a set of records and want to avoid the N+1 query problem, where N is the number of records in the result set.

Eager loading reduces the number of database queries and can significantly improve the performance of your application when dealing with relationships. It's especially beneficial in situations where you're loading multiple records with their related data.

Example of eager loading in Laravel:

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

In this example, the with() method loads the comments for all the retrieved posts in a single query, rather than running one query to fetch the posts and then N additional queries to fetch the comments for each post.

Statamic Ninja

Comments

Marian Pop

PHP / Laravel Developer. Writing and maintaining @LaravelMagazine. Host of "The Laravel Magazine Podcast". Pronouns: vi/vim.

Subscribe to our newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.

Weekly articles
We send a new issue of the newsletter every week on Friday.
No spam
We'll never share your email address and you can opt out at any time.