Swaz's avatar
Level 20

Using whereHas() and with()

Is there a way to use whereHas() and with() but retain the where()? I know I can do this but I was wondering if there is a better way.

$posts = Post::whereHas('comments', function ($query) {
        $query->where('content', 'like', 'foo%');
})->with(['comments' => function ($query) {
        $query->where('content', 'like', 'foo%');
}])->get();
0 likes
3 replies
bobbybouwmann's avatar

If you don't want to add a scope, like the link of bestmomo showed you can do something like this as well

$callback = function($query) {
    $query->where('something', '=', 'something');
}

$posts = Post::whereHas('comments', $callback)->with(['comments' => $callback])->get();
10 likes

Please or to participate in this conversation.