Eager loading in Laravel is a technique used to solve the "N+1 query problem" in database interactions, particularly with ORM (Object-Relational Mapping) tools like Eloquent. The N+1 query problem occurs when your application makes one query to retrieve the initial set of records (for example, posts), and then for each record, it makes another query to fetch related records (for example, comments on each post). If you have N posts, this results in 1 query to fetch the posts plus N additional queries to fetch comments for each post, hence the name "N+1 query problem."
Eager loading solves this problem by retrieving the related records for all of the initial records in a single query. This means get all comments related to posts instead of n number of queries This significantly reduces the number of queries made to the database, improving the performance and scalability of your application.
Simple Example without Eager Loading
Check this code. This is our controller function
public function index()
{
$posts = Post::all();
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->body;
}
}
}
We have checked this with debug tool. And here is result.
This database has 245 posts
So inside every iteration inside the loop Laravel runs a query and get comments for the post. So it means 245 queries for 245 posts. This is default behavior and it is called lazy loading.
Implementing Eager Loading
You can use eager loading to preload the Comments for all Posts in a single query using the with() method:
public function index()
{
$posts = Post::with('comments')->get();
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->body;
}
}
}
See now it is just 4 queries.
It gets all post id's and get comments with a single query. This is called eager loading.
Top comments (0)