Differences between lazy loading and eager loading

Marian V. Pop
2 min readOct 26, 2023

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:

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

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.

--

--

Marian V. Pop

🧙‍♂️ PHP / @Laravel Developer ✍🏻 Writing and maintaining @LaravelMagazine 🎙 Host of “The Laravel Magazine Podcast”. 👤 Pronouns: vi/vim