PHP
Eager Loading Relationships to Solve N+1 Problem in Laravel
Optimize your Laravel application's performance by eager loading Eloquent relationships using the `with()` method, effectively preventing the common N+1 query problem and reducing database load.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class User extends Model
{
use HasFactory;
public function posts()
{
return $this->hasMany(Post::class);
}
}
// --- Example of N+1 problem (bad): ---
// $posts = Post::all(); // 1 query
// foreach ($posts as $post) {
// echo $post->user->name; // N queries, one for each user
// }
// --- Solving with Eager Loading (good): ---
// Load posts and their associated users in just 2 queries
$postsWithUsers = Post::with('user')->get(); // 1 query for posts, 1 for users
foreach ($postsWithUsers as $post) {
echo $post->user->name; // No additional queries here
}
// Eager loading multiple relationships:
$postsWithUsersAndComments = Post::with(['user', 'comments'])->get();
// Eager loading with constraints:
$postsWithActiveComments = Post::with(['comments' => function ($query) {
$query->where('status', 'active');
}])->get();
How it works: The N+1 query problem occurs when retrieving a list of models and then, in a loop, fetching a related model for each. This results in N additional queries. Eager loading relationships with Eloquent's `with()` method solves this by fetching all related models in a separate, single query. This dramatically reduces the number of database queries and significantly improves application performance.