Discover how a simple change can make your app lightning fast and save hours of debugging!
Why Eager loading (with) in Laravel? - Purpose & Use Cases
Imagine you have a blog with posts and each post has many comments. You want to show a list of posts with their comments. So, you write code that fetches each post, then for each post, you fetch its comments separately.
This means if you have 10 posts, you run 1 query to get posts and then 10 more queries to get comments for each post. This is slow and wastes resources. It also makes your app feel laggy and can crash if there are many posts.
Eager loading lets you tell Laravel to get posts and their comments in just 2 queries: one for posts and one for all related comments. This is faster, cleaner, and uses less memory.
$posts = Post::all();
foreach ($posts as $post) {
$comments = $post->comments;
}$posts = Post::with('comments')->get();
Eager loading makes your app faster and smoother by reducing database queries automatically.
When showing a product list with reviews on an online store, eager loading fetches all products and their reviews efficiently, so customers see everything instantly.
Manual fetching causes many slow database queries.
Eager loading fetches related data in fewer queries.
This improves app speed and user experience.