PHP
Eager Loading Relationships with Specific Conditions in Laravel Eloquent
Optimize database queries by eager loading related models only if they meet specific criteria, preventing N+1 problems and fetching relevant data efficiently.
use App\Models\Post;
use App\Models\Comment;
$postsWithApprovedComments = Post::with(['comments' => function ($query) {
$query->where('is_approved', true)->orderByDesc('created_at');
}])->get();
foreach ($postsWithApprovedComments as $post) {
echo "Post: " . $post->title . "
";
foreach ($post->comments as $comment) {
echo "- Approved Comment: " . $comment->body . "
";
}
}
How it works: This snippet demonstrates how to eager load a relationship (`comments` on `Post`) while applying specific constraints to the related models. By passing a closure to the `with()` method, you can add `where`, `orderBy`, or any other query builder methods to filter the comments that are loaded. This is crucial for avoiding the N+1 query problem and fetching only the relevant related data, significantly improving application performance.