Reputation: 1208
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
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