PHP

Efficiently Prevent N+1 Queries with Eloquent Eager Loading

Learn how to optimize your Laravel application's performance by preventing the N+1 query problem using Eloquent's `with()` method for eager loading relationships.

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

// Good: Eager loading
$posts = App\Models\Post::with('user')->get();
foreach ($posts as $post) {
    echo $post->user->name; // User is already loaded, no extra queries
}

// Eager loading multiple relationships
$orders = App\Models\Order::with(['customer', 'products'])->get();

// Nested eager loading
$comments = App\Models\Comment::with('post.user')->get();

// Eager loading with constraints
$users = App\Models\User::with(['posts' => function ($query) {
    $query->where('active', 1)->orderBy('created_at', 'desc');
}])->get();
How it works: Eager loading solves the N+1 query problem, a common performance bottleneck where accessing a relationship on multiple models triggers a separate database query for each model. By using the `with()` method, Eloquent pre-loads all specified relationships in a minimal number of queries (typically two: one for the parent models and one for each relationship), drastically improving application speed, especially when dealing with large datasets. You can eager load multiple relationships, nested relationships, and even add constraints to the eager loaded query.

Need help integrating this into your project?

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

Hire DigitalCodeLabs