Level 60
$categories = [2, 3];
$posts = Post::with(['categories' => function($q) use ($categories) {
$q->whereIn('id', $categories);
}]);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have Post and Category models. One post can have many categories so I have many to many relationship stored in table named postsCategories.
postsCategories table has the following attributes: id, category_id, post_id
Post model:
public function categories()
{
return $this->hasMany('App\PostCategory', 'post_id', 'id');
}
Now, in my controller I have an array wih a list of category IDs:
$categories = array(2, 3)
I want to fetch all posts that are in category 2 and 3 in the same controller. How can I create the query that filters the posts with $categories array?
Please or to participate in this conversation.