Denis2310
Denis2310

Reputation: 1208

Show Posts By Multiple Tags specified (Laravel 5.6)

I want to show only posts that are related to multiple tags. Posts and tags are connected with many to many relationship.

In filter menu user can check multiple tags and then only posts that are related to all of those tags needs to be shown.

For example: If user checks #fruit and #vegetable tags then posts with both of those tags will appear.

whereIn('tag_id', $array_of_tag_ids) method is working but its showing all posts that have at least one tag of those specified.

Thanks

Upvotes: 0

Views: 597

Answers (1)

IndianCoding
IndianCoding

Reputation: 2683

You can use foreach with whereHas.

$tags = $request->input('tags');

$posts = Post::when($tags, function($query) use ($tags){
             foreach($tags as $tag){
                 $query->whereHas('tags', function($query) use ($tag){
                     $query->where('id', $tag);
                 });
             }
         })
         ->get();

Upvotes: 1

Related Questions