Performance: Eager loading (with)
Eager loading reduces the number of database queries, improving page load speed and interaction responsiveness.
$posts = Post::with('author')->get(); foreach ($posts as $post) { echo $post->author->name; }
foreach ($posts as $post) {
echo $post->author->name;
}| Pattern | Database Queries | Network Requests | Server Response Time | Verdict |
|---|---|---|---|---|
| Lazy loading (accessing relations inside loop) | N+1 queries | Multiple | High | [X] Bad |
| Eager loading with 'with' method | 2 queries | Few | Low | [OK] Good |
with() in Laravel Eloquent queries?with() doeswith() method tells Laravel to load related models eagerly, meaning it fetches them in the same database query or fewer queries.with() method to eager load relationships before fetching results.Post::with('comments')->get(); correctly calls with() and then get() to retrieve posts with comments. $users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count();
}with('posts') loads all posts for each user in one query, so $user->posts is available without extra queries.$user->posts->count() returns the number of posts related to that user, printed one by one.$orders = Order::with('customer')->get();
foreach ($orders as $order) {
echo $order->customer->name;
}with('customer') is correctly used before get(), so related customers are loaded.$order->customer could be null, causing an error when accessing name without a check.with(['comments.author']).load() statically, which is invalid as load() is an instance method. Post::with(['comments', 'author'])->get(); loads comments and author separately as array elements, but author is not direct relation. Post::with(['comments.author'])->get(); correctly loads comments and their author nested.Pass the test and this pattern moves unknown