2
votes

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.

1
you need to add where condition in your with statement to apply filter in relational data not in whereHas.Bhaumik Pandhi
are you sure you passing value to $sort = 'answered' ??Hamelraj

1 Answers

1
votes

You must apply the same condition in with for achieving this. Example,

$posts = Post::with(['comments' => function($q) use($sort, $search) {
       if($sort === 'answered'){
            $q->where('answered', '=', 1);
        }
        if($search){
            $q->where('content', 'like', '%'.$search.'%');
        }
    }])
    ->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);

I think this will solve your issue. and let me know if it is working