PHP
Efficiently Eager Load Multiple Eloquent Relationships with Constraints
Optimize database queries by eager loading multiple related models with specific conditions, preventing N+1 problems and improving application performance.
use App\Models\Post;
// Load 'author' and 'comments', with a constraint on 'comments'
$posts = Post::with([
'author',
'comments' => function ($query) {
$query->where('approved', true)->latest();
}
])->get();
foreach ($posts as $post) {
echo "Post: " . $post->title . "
";
echo "Author: " . $post->author->name . "
";
foreach ($post->comments as $comment) {
echo "- Comment: " . $comment->body . "
";
}
}
// Lazy eager loading: load related data on already retrieved models
$singlePost = Post::find(1);
$singlePost->load([
'tags' => function ($query) {
$query->where('active', true);
}
]);
// $singlePost->tags is now loaded with active tags
How it works: This snippet demonstrates how to eagerly load multiple related models using the `with()` method, which prevents the N+1 query problem. It also shows how to add constraints to an eager-loaded relationship, such as filtering approved comments and ordering them. Additionally, it includes an example of lazy eager loading using `load()` to fetch related models for an already retrieved single model or collection of models.