PHP

Optimize Query Performance with Eloquent Eager Loading

Learn how to prevent the N+1 query problem in Laravel Eloquent by using eager loading to efficiently fetch related models and improve application speed and database efficiency.

// In your Post model, define the relationship:
// public function user() { return $this->belongsTo(App\Models\User::class); }
// public function comments() { return $this->hasMany(App\Models\Comment::class); }

// Without eager loading (N+1 problem) - Example (avoid in production):
// $posts = App\Models\Post::all();
// foreach ($posts as $post) {
//     echo $post->user->name; // Each access to $post->user executes a separate query
//     foreach ($post->comments as $comment) {
//         echo $comment->body;
//     }
// }

// With eager loading (recommended):
$posts = App\Models\Post::with(['user', 'comments'])->get();

foreach ($posts as $post) {
    echo $post->user->name . "
";
    foreach ($post->comments as $comment) {
        echo "- " . $comment->body . "
";
    }
}
How it works: This snippet demonstrates how to use Eloquent's `with()` method for eager loading. Instead of executing a separate query for each related model (a common pitfall known as the 'N+1 problem'), `with()` fetches all specified relationships in a single, more efficient query. This significantly reduces the total number of database queries and vastly improves the performance of your application when displaying lists of models with their related data, preventing unnecessary database load.

Need help integrating this into your project?

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

Hire DigitalCodeLabs