1

I made a Laravel project where Category, Subcategory and Child category working using same table relation. I want to show all products from childcategory when click to Main Category. So for that I need to use multiple foreach loop like this,

foreach ($categories->subcategories as $subcat)
{
foreach ($subcat->childcategories as $childcat )
{
$products = $childcat->products;
}
}

Now I want to send $products to a view. How can I do it. I don't want to use array. How can I send It. Please help.

2 Answers2

0

Use Array()

$products = array()
foreach ($categories->subcategories as $subcat)
{
foreach ($subcat->childcategories as $childcat )
{
     $products[] = $childcat->products;
}
}
return view(....);
KpStar
  • 122
  • 7
  • I did it but then I can't sort product like Eloquent Collection. – Abir Husain Jan 20 '22 at 08:27
  • I learn a way to sort array using collect() method. So now I don't need to send products directly to view. I can use array what you suggest in your answer and can sort like this $child = collect($child)->sortBy('price')->reverse()->toArray(); So I accepted your Answer. – Abir Husain Jul 16 '22 at 07:50
0

In Laravel you can pass your Category Object to the view. In Blade you have access to the relationships of Category. You can testet by :

dd($categories->subcategories) or dd($categories->subcategories[]->childcat).

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • But problem is I can't use pagination for product if I do this. – Abir Husain Jan 20 '22 at 08:25
  • @AbirHusain Of course you can also do this via paginate :-) – Maik Lowrey Jan 20 '22 at 08:33
  • Can you please explain how can I paginate products If I send Categories to the view. Because If I send $products object with paginate () method then I can use $products->links() for pagination in view. How Can I do this if I send Category object ? – Abir Husain Jan 20 '22 at 08:51
  • @AbirHusain this is a completely new question. your question above was: "How to send relational data from multiple foreach to view in Laravel". The best thing to do is to ask a completely new question, but first think about what other difficulties might arise and define your new question accordingly. That makes more sense than debugging your code here in the comments ;-) – Maik Lowrey Jan 20 '22 at 08:57
  • Thank you for reply.But your answer was not related to my questions. I don't need to use foreach loop If I want to send Categories. I want to send $products from multiple foreach. – Abir Husain Jan 20 '22 at 13:22
  • @AbirHusain I see. That was not quite clear to me. Question: In this case, what prevents you from calling up the product model in the controller and sending it? `Product::paginate(10)`. – Maik Lowrey Jan 20 '22 at 13:29