tehseen's avatar

Get all product related to category ids

I need to get all product related to category id in my many to many relationship but i have not succeed yet any help please.

 $ProductCategories = $product->categories;

        $productsOfThisCategory = array();
        foreach($ProductCategories as $category) {
            $productsOfThisCategory[] = $category->products();
        }

        dd($productsOfThisCategory);

all categories are in $ProductCategories var but when in apply foreach and get product related to it will give me relationship but no product why ?

0 likes
8 replies
Sinnbeck's avatar

This part is calling a function (most likely a query builder)

 $category->products();

//Should be
 $category->products;

Also, I hope that you preload your relations? If not this will give you alot of database queries.

tehseen's avatar

my bad i did not see the function :'(

tehseen's avatar

So if i have multiple product categories and with multiple collection how i can merge all and give a single array or collection do view for example

I have the two categories and it will give me correct results like belwo

array:2 [▼
  0 => Collection {#328 ▼
    #items: array:5 [▶]
  }
  1 => Collection {#341 ▼
    #items: array:1 [▶]
  }
]

so how i can can make a single 5+1 array and pass to view ?

Sinnbeck's avatar

If you need to do it like that, this should work (if I knew more about you actual data, it could probably be done much simpler, by simply getting all product category Ids, and then running a whereIn on Product::

$productsOfThisCategory = collect([]);
        foreach($ProductCategories as $category) {
            $productsOfThisCategory->merge($category->products);
        }
tehseen's avatar

i try the above but it gives me

Collection {#315 ▼
  #items: []
}
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Oh sorry forgot that it does not mutate

$productsOfThisCategory = collect([]);
        foreach($ProductCategories as $category) {
            $productsOfThisCategory = $productsOfThisCategory->merge($category->products);
        }
tehseen's avatar

Yes this works Great. Any idea how to exclude the item which repeat again i mean every category ?

Sinnbeck's avatar

try using unique

$productsOfThisCategory = $productsOfThisCategory->unique('id')->values()->all();

Please or to participate in this conversation.