Support the ongoing development of Laravel.io →
posted 9 years ago
Blade
Last updated 2 years ago.
0
Solution

One way is to prepare your data first

foreach ($products as $product) {
$category[$product->category_id][] = $product;
}

and then display the products in your view for each category id.

Last updated 2 years ago.
0

Thanks ! Working like a charm

Last updated 2 years ago.
0

ok. i will try to give an example based on you sample code. First in the controller we prepare data to our needs

           foreach($results as $result) {
               $categories[$result->category_id]['name'] = 'Category name for the specific category id from db using eloquent or something';
               $categories[$result->category_id]]['products'][] = $row;
           }

And then in view we iterate through the arrays

           //iterate categories array
           @foreach($categories as $category_with_products) 
               {{ $category_products['title'] }}
               //iterate products array of objects for the specific category
               @foreach($category_products['products'] as $product)
                   {{ $product->name }}
               @endforeach              
           @endforeach

Hope that helps. I have checked the code and it is working as expected.

Last updated 2 years ago.
0

lorienhd said:

Thanks ! Working like a charm

It seems that you figured out what to do while i was elaborating more on the issue ;-)

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

lorienhd lorienhd Joined 20 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.