0

I want to filter replies based on query parameter passed, query parameters can be post_id, comment_id and array of reply_ids all can be optional and can be used as combination

 $query = Post::where('user_id', auth()->id());
    if ( isset($data['reply_ids']) ) {
        $query = $query->with('posts.comments.replies')->whereHas('posts.comments.replies', function($query) use ($data){
            $query->whereIn('id', $data['reply_ids']);
        });
    }

Now, if I want to filter again with comment authors, that is on comments table, if I want to add filters of post author, that will be on posts table, how I can add those conditional, and still that will be optional?

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105

2 Answers2

0

Just add another if statements below. Those will be optional, sice you define your $query before your first filtering action.

Norbert Jurga
  • 204
  • 4
  • 14
0

I needed to use another eager loading with so that the query will be build on all the combination selected, so the final code will be something like

$query = Post::where('user_id', auth()->id());
if ( isset($data['reply_ids']) ) {
    $query = $query->with('posts.comments.replies')->whereHas('posts.comments.replies', function($query) use ($data){
        $query->whereIn('id', $data['reply_ids']);
    });
}
$query = $query->with(['posts' => function($query){ $query->where('status', 'pending'); }])

$query->get()
Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105