I have problem with my Laravel project. I have model Post and Comment. One post has many comments and this is relation in my Post comment. When When I want get all posts and comments all works great:
$posts = Post::with('comments')
->orderBy('id', 'desc')
->paginate(10);
I have problem because I want write search engine to models. I want get only posts and only comments where search condition for comments if true. I try this code:
$posts = Post::with('comments')
->whereHas('comments', function($q) use($sort, $search){
if($sort === 'answered'){
$q->where('answered', '=', 1);
}
if($search){
$q->where('content', 'like', '%'.$search.'%');
}
})
->orderBy('id', 'desc')
->paginate(10);
But this code return all comments to post, not only comments where condition is true.
where
condition in yourwith
statement to apply filter in relational data not inwhereHas
. – Bhaumik Pandhi$sort = 'answered'
?? – Hamelraj