I'm trying to use a database to add menu items on a sidebar on my site. My database is structured as follows:
ID / Product_Name/ Product_Type
1 / product1 / type1
2 / product2 / type1
3 / product3 / type2
4 / product4 / type2
I need a sidebar which has each type listed as a menu item, with the products belonging to that type as the submenu items:
Type1
product1
product2
Type2
product3
product4
With my current code however I achieve each menu item but my submenu shows every product in the entire database instead of just the products belonging to that type.
My controller:
public function index()
{
//get all products
$products = Product::all();
//get each type
$types = Product::distinct()->get(['Type']);
return view('pages.getstarted')->with('products', $products)
->with('types', $types);
}
My view:
<ul class="list-sidebar">
@foreach($types as $type)
<li class="header">
<a href="#" data-toggle="collapse" data-target="#1">{{$type->Type}}<span class="fa fa-chevron-left pull-right"></span></a>
<ul class="sub-menu collapse" id="1">
@foreach($products as $product)
<li><a href="1">{{$product->Product_Name}}</a></li>
@endforeach
</ul>
</li>
@endforeach
</ul>
I am very new to Laravel so any help would be appreciated.
Just change your controller and your view a bit with the groupBy method from the Collection instance:
Documentation
Controller
public function index()
{
//get all products
$products = Product::all();
return view('pages.getstarted')->with('products', $products);
}
View
<ul class="list-sidebar">
@foreach($products->groupBy('Product_Type') as $type => $subCollection)
<li class="header">
<a data-target="#1" data-toggle="collapse" href="#">
{{$type}}
<span class="fa fa-chevron-left pull-right"></span>
</a>
<ul class="sub-menu collapse" id="1">
@foreach($subCollection as $product)
<li>
<a href="1">{{$product->Product_Name}}</a>
</li>
@endforeach
</ul>
</li>
@endforeach
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With