I am having trouble looping through a multidimensional array with blade in laravel. I am sending the data from the controller like so:
return View::make('store.categories')
->with('brands', $brands);
And if I die dump the data:
array (size=2)
0 =>
array (size=2)
0 => string 'Fender' (length=6)
1 => string '(2)' (length=3)
1 =>
array (size=2)
0 => string 'Gibson' (length=6)
1 => string '(1)' (length=3)
I've tried to use two @foreach loops but I couldn't get it to work:
@foreach($brands as $brand)
@foreach($brand as $b)
{{$b}}
@endforeach
@endforeach
The above will output: Fender (2) Gibson (1).
I tried to get the 0 value for the
$b to output Fender but it just prints the 0 position character for each of the items in the $b array:
@foreach($brands as $brand)
@foreach($brand as $b)
{{$b[0]}}
@endforeach
@endforeach
The above will output F ( G (.
In my controller if I do:
foreach ($brands as $b) {
foreach($b as $key=>$v) {
dd($v);
}
}
it will output string 'Fender' (length=6), which seems like the second loop inside the first @foreach works. Although, when it comes to the blade code mentioned above it doesn't.
I'm probably doing something terribly wrong. How can I get the output for the values 0 and 1 for the nested arrays individually? Any help is highly appreciated.
This is how I create the data in my controller's function:
$products = Product::with('brand')->whereIn('category_id', $children->lists('id'));
$brand_ids = array();
$brands = array();
foreach ($products->get() as $p) {
$brand_ids[] = $p->brand_id;
}
$brand_count = array_count_values($brand_ids);
foreach ($brand_count as $key=>$value) {
$query = Brand::where('id', '=', $key)->lists('name');
// dd($query);
foreach($query as $key=>$name) {
$array = array(
$name,
'('.$value.')'
);
$brands[] = $array;
}
}
[in the view.brandsdata?arrayposition0and1, so for example the first time it loops{{b[0]}}outputsFenderandb[1]outputs(2), the second time{{b[0]}}outputsGibsonandb[1]outputs(1)