PHP

Eager Loading Related Models to Prevent N+1 Queries

Optimize Laravel Eloquent queries by eager loading related models using `with()` to prevent performance-impacting N+1 query problems, ensuring efficient data retrieval.

<?php

// Bad: N+1 problem - Each user->posts access triggers a new query
$users = App\Models\User::all();
foreach ($users as $user) {
    echo $user->posts->count();
}

// Good: Eager loading with 'with()'
// Fetches all users and their posts in just two queries
$users = App\Models\User::with('posts')->get();
foreach ($users as $user) {
    echo $user->posts->count(); // Posts are already loaded
}

// Eager loading multiple relations
$products = App\Models\Product::with(['category', 'tags'])->get();

// Eager loading with constraints on the related model
$usersWithPublishedPosts = App\Models\User::with(['posts' => function ($query) {
    $query->where('published', true);
}])->get();

// Nested eager loading
$orders = App\Models\Order::with('customer.address')->get();
How it works: This snippet demonstrates eager loading related models using Eloquent's `with()` method. Eager loading fetches all related records in a single or a few separate queries, drastically reducing the number of database queries (the 'N+1 problem') compared to lazy loading, where each relation access triggers a new query. This significantly improves application performance, especially when displaying lists of models and their relationships. You can eager load multiple relations, nest them, and even add constraints to the eager-loaded queries.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs