Many to Many whereHasAll

Posted 4 months ago by ahmeddabak

I have the following situation, a website has over 38,000 posts and each of them has many tags.

The relation is many to many.

I need a search bar where i can write "future tech -robots", So the result must be posts that have "future" and "tech" as tags, but not "robots".

My solution was

$result = Post::whereHas('tags', function($query) {
    $query->whereIn('tag_id', $tags);
})->get();

and then to filter the $result collection. but here i get posts that have any of the tags "future" and "tech", and not the ones that have all of them.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.