2

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.

2
  • 1
    you need to add where condition in your with statement to apply filter in relational data not in whereHas. Commented Feb 26, 2020 at 10:32
  • are you sure you passing value to $sort = 'answered' ?? Commented Feb 26, 2020 at 10:32

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.