Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

liandhas's avatar

Nested foreach Loop

@foreach($mainCatg->get() as $m)
    {{$m->catg_name}}
    @foreach($subCatg->where('catg_name',$m->catg_name)->get() as $s)
    {{$s->catg_name}}
    @endforeach
@endforeach

I have an issue with this code. I didn't get the result of the 2nd loop. It just shows empty.

0 likes
3 replies
bobbybouwmann's avatar
Level 88

First's of all it's a really bad practice to perform queries inside your views. There are better ways of doing this.

The reason your code doesn't return anything is probably that the query return an empty result. What is $subCatg here?

liandhas's avatar

Yes, It was bad practice. I changed it after I see your reply post. Thank you!

Now, I stored these values as a category of each product in a cell using json_encode, how to fetch these values as a Tree?

{"main_catg":"Home Appliances","sub_catg":"Coffee Makers"}
{"main_catg":"Home Appliances","sub_catg":"Tea Makers"}
{"main_catg":"Home Appliances","sub_catg":"Tea Makers"}

I am not an expert in coding.

bobbybouwmann's avatar

You can probably just return them as an array to your view. This way you only need one foreach loop.

Can you show your controller code?

Please or to participate in this conversation.