Performance: Lazy loading and N+1 prevention
This concept affects database query efficiency and page load speed by reducing unnecessary data fetching and minimizing server response time.
$posts = Post::with('author')->get(); foreach ($posts as $post) { echo $post->author->name; }
foreach ($posts as $post) {
echo $post->author->name;
}| Pattern | Database Queries | Server Response Time | Page Load Impact | Verdict |
|---|---|---|---|---|
| Lazy loading causing N+1 queries | N+1 queries (1 + N) | High due to many queries | Slower LCP, delays content display | [X] Bad |
| Eager loading with with() method | 2 queries (main + related) | Low due to fewer queries | Faster LCP, quicker content display | [OK] Good |
with() in Laravel Eloquent queries?with()with() method loads related models eagerly in one query, preventing multiple queries.with() usage [OK]with() to load relations early and avoid many queries [OK]with() delays loadingwith() deletes datawith() with paginationwith() to eager load relations, not load() or others in this context.with('comments') is called before get() to eager load comments with posts.with() before get() [OK]with() before get() for eager loading [OK]load() statically instead of on model instanceeager() or fetch()with() after get()$users = User::all();
foreach ($users as $user) {
echo $user->posts->count();
}
User::all() runs 1 query to get all users.$user->posts triggers a query per user (lazy loading), causing N additional queries.with() causes N+1 queries [OK] $orders = Order::with('items');
foreach ($orders as $order) {
echo $order->items->count();
}Order::with('items') builds a query but does not execute it without get() or similar.get(), $orders is a query builder, not a collection, so foreach will error.get() after with() to execute the query -> Option Dget() to run query after with() [OK]get() after with() to fetch data [OK]get()with() runs query immediatelywith('books.reviews') to eager load books and their reviews together, preventing multiple queries.with() [OK]with() for nested relations [OK]with('reviews') loads nested reviewsPass the test and this pattern moves unknown