PHP

Optimizing Eloquent Queries with Eager Loading

Prevent N+1 query problems by efficiently loading related Eloquent models with a single query using eager loading (`with()` method). Essential for performance.

<?php

use App\Models\Post;
use App\Models\User;

// Bad: N+1 problem (separate query for each post's user)
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->user->name; // Each access triggers a new query
}

// Good: Eager loading 'user' relationship
$postsWithUsers = Post::with('user')->get();
foreach ($postsWithUsers as $post) {
    echo $post->user->name; // User is already loaded
}

// Eager loading multiple relationships
$postsWithUsersAndComments = Post::with(['user', 'comments'])->get();
foreach ($postsWithUsersAndComments as $post) {
    echo $post->user->name;
    foreach ($post->comments as $comment) {
        echo $comment->body;
    }
}

// Eager loading with constraints
$postsWithActiveComments = Post::with(['comments' => function ($query) {
    $query->where('is_active', true);
}])->get();
How it works: Eager loading is crucial for preventing the "N+1 query problem," which occurs when fetching a collection of models and then iterating over them to access a related model, causing an additional query for each item. The `with()` method tells Eloquent to load specified relationships for all retrieved models in a single query. This significantly reduces the number of database queries, dramatically improving application performance. You can also apply constraints to eager-loaded relationships.

Need help integrating this into your project?

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

Hire DigitalCodeLabs