PHP
Efficient Eager Loading with Constraints
Optimize Laravel Eloquent queries by eager loading relationships with specific conditions and nested relationships to prevent N+1 query problems efficiently.
// In a Controller or Service
$users = App\Models\User::with(['posts' => function ($query) {
$query->where('published_at', '<=', now());
}])->with('posts.comments') // Nested eager loading
->get();
// Example Model relationships
// User.php
// public function posts() { return $this->hasMany(Post::class); }
// Post.php
// public function user() { return $this->belongsTo(User::class); }
// public function comments() { return $this->hasMany(Comment::class); }
How it works: This snippet demonstrates how to eager load related models with specific conditions (constraints) and also how to eager load nested relationships. The `with(['posts' => function ($query) { ... }])` syntax allows you to add `WHERE` clauses to the `posts` relationship's query, ensuring only relevant posts are loaded. `with('posts.comments')` then loads the comments for each eagerly loaded post, preventing further N+1 issues for comments.