Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mleontenko's avatar

Query by related model attributes

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?

0 likes
2 replies
Sergiu17's avatar
$categories = [2, 3];

$posts = Post::with(['categories' => function($q) use ($categories) {
	$q->whereIn('id', $categories);
}]);
Sinnbeck's avatar

use whereHas

$categories = array(2, 3);

$posts = Post::whereHas('categories', function($query) use ($categories) {
	$query->whereIn('id', $categories);
});

Please or to participate in this conversation.