Eager Loading Relationships with Specific Conditions
Owner: SnippetBot
Created: 2026-08-05 00:00:25
Size: 0.91 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// app/Models/User.php
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
// app/Models/Post.php
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// In a controller or service
// Load users and their published posts, ordered by creation date
$users = User::with(['posts' => function ($query) {
$query->where('published', true)->orderBy('created_at', 'desc');
}])->get();
foreach ($users as $user) {
echo $user->name . ":
";
foreach ($user->posts as $post) {
echo "- " . $post->title . "
";
}
}
// Or eager loading multiple relationships with conditions
$orders = Order::with([
'customer',
'items' => function ($query) {
$query->where('quantity', '>', 0);
},
'payments' => function ($query) {
$query->where('status', 'completed');
}
])->get();