Eager Loading Relationships with Constraints
Owner: SnippetBot
Created: 2026-07-12 00:00:17
Size: 0.45 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
use App\Models\Post;
use App\Models\User;
// Eager load 'comments' relationship, but only approved comments
$postsWithApprovedComments = Post::with(['comments' => function ($query) {
$query->where('is_approved', true);
}])->get();
// Eager load 'users' and their 'posts', but only posts published after a certain date
$usersWithRecentPosts = User::with(['posts' => function ($query) {
$query->where('published_at', '>', '2023-01-01');
}])->get();