PHP
Eager Load Eloquent Relationships to Solve N+1 Problem
Optimize Laravel Eloquent queries by eager loading relationships with the `with()` method, drastically reducing database calls and improving application performance.
// In your User model
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
// In your Post model
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// Without eager loading (N+1 problem)
// $users = User::all();
// foreach ($users as $user) {
// echo $user->posts->count(); // Each user's posts query runs separately
// }
// With eager loading
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count(); // Posts are loaded efficiently in one extra query
}
// Eager loading multiple relationships
// $users = User::with(['posts', 'comments'])->get();
// Eager loading with constraints
// $users = User::with(['posts' => function ($query) {
// $query->where('published', true);
// }])->get();
How it works: Eager loading relationships with `with()` prevents the 'N+1 problem' by loading all related models in a single, separate database query instead of executing a query for each parent model. This significantly reduces the total number of database queries, improving the performance and responsiveness of your Laravel application when accessing related data.