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

manojo123's avatar

Get all possible elements from belongsToMany Relationship

Hello community,

I have 3 tables

products categories category_product

Given I have a collection with categories

$category = Category::findMany([1, 2]);

I want to get all possible products from both categories in a collection

So far i am creating a foreach loop and combining arrays but want a cleaner way if possible

Thanks in advance.

0 likes
4 replies
manojo123's avatar

@marianomoreyra Thanks for the reply:

In your case you are considering the product collection separately in each category. I need all products from category 1 and 2 together in the same collection

I dropped my loop and now I am using this logic

Product::whereIn(
   'id',
   CategoryProduct::whereIn('category_id', [1, 2])->pluck('product_id')
)->get(); 

Where CategoryProduct is a pivot model class that I just created. I think thats it.

SilenceBringer's avatar
Level 55

Hi @manojow

$products = Product::whereHas('categories', function ($query) {
    $query->whereIn('id', [1, 2]);
});

Please or to participate in this conversation.