One of the most frequent performance bottlenecks in Laravel applications is the notorious N+1 query problem. It occurs when your code loops through Eloquent models and executes a separate database query on every iteration instead of retrieving related records up front.
Understanding the N+1 Problem
Imagine displaying a list of 25 articles along with each author's name inside a loop. Without eager loading, Laravel runs 26 database queries: 1 query to fetch the articles, plus 25 additional queries for each individual author. By applying eager loading via the with() method, Laravel consolidates this entire operation into just 2 optimized queries.
// Bad: Triggers the N+1 problem (26 queries)
$articles = Article::all();
foreach ($articles as $article) {
echo $article->author->name;
}
// Good: Eager loading (only 2 queries)
$articles = Article::with("author")->get();
foreach ($articles as $article) {
echo $article->author->name;
}Key Takeaways for Developers
- Use
with()whenever you know views, APIs, or response payloads require related models. - Load deeply nested relationships cleanly using dot notation, such as
with("comments.user"). - In local development environments, add
Model::preventLazyLoading(!app()->isProduction())to yourAppServiceProviderto catch accidental lazy loading immediately.