Nope, not a bug. The closure only works on the eager loaded resource. Look at the has() and whereHas() methods to achieve what you want. It's on the same docs page: http://laravel.com/docs/eloquent#querying-relations
$users = User::whereHas('posts', function($q)
{
$q->where('title', 'like', '%first%');
})->get();
@shabushabu not entirely true:
@l4zl0w To get what you wanted, do as shabu said. But still you can use the same construct to limit loaded posts:
$users = User::whereHas('posts', function($q)
{
$q->where('title', 'like', '%first%');
})->with('posts')
->get();
// loads only users that have related posts matching given title but with all related posts
$users = User::with( ['posts' => function($q)
{
$q->where('title', 'like', '%first%');
] })->get();
// loads only all the users and ONLY related posts matching given title
$users = User::with( ['posts' => function($q)
{
$q->where('title', 'like', '%first%');
]})
->whereHas('posts', function($q)
{
$q->where('title', 'like', '%first%');
})->get();
// a combination of the two: only users that have the matching posts, and only those posts
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.