Level 88
You should use has here!
Documentation: https://laravel.com/docs/5.6/eloquent-relationships#querying-relations
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello Guys , I have a question . I have those tables -
Post PostCategory ( belongsTo Post ) PostTags ( belongsToMany Post )
And I want to -
Search those
POSTS that has
PostCategory with id ( PostCategory ID ) 1 and 2 and
PostTags with id ( PostTags ID ) 2 and 3
So I can do like this -
$post_category_ids = [1,2];
$post_tags_ids = [2,3];
Post::select(['id', 'status' , 'title' , 'description' ])
->when($post_category_ids, function ($query) use ($post_category_ids) {
return $query->whereIn('id' , $post_category_ids);
})
->when($post_tags_ids , function ($query) use ($post_tags_ids ) {
HOW COULD I DO IT WITH BELONGS TO MANY HERE ?
})
->get()
thanks
Please or to participate in this conversation.