Home > Software engineering >  How to send relational data from multiple foreach to view in Laravel
How to send relational data from multiple foreach to view in Laravel

Time:01-20

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.

CodePudding user response:

Use Array()

$products = array()
foreach ($categories->subcategories as $subcat)
{
foreach ($subcat->childcategories as $childcat )
{
     $products[] = $childcat->products;
}
}
return view(....);

CodePudding user response:

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).

  •  Tags:  
  • Related