Home > OS >  Grouping items of the same category type in blade
Grouping items of the same category type in blade

Time:04-16

I have this method that returns the services being offered

public function order_services(){
    
    $services = DB::select('select * from services');
    return view('guests/services',['services'=>$services]);;

}

and i am displaying like this

<ul  id="myUl">
   @foreach ($services as $service)
   <li ><span  style="font-size:24px; color:red
      "><i ></i></span> <span style="font-weight:bold" id="service_category">{{ $service->service_category }}</span><span><u><i ></i></u></span></li>
   <li ><span  style="font-size:24px; color:#870FD1" data-price="349.34"><i ></i></span> <span  id="service_name" data-price="{{ $service->service_price }}" data-category="{{ $service->service_category }}" >{{ $service->service_name }}</span><span ><u>Available</u></span></li>
   @endforeach
</ul>

My table has service_name and service_category

I would like to display service_category as header and all the services under that category. Can this be done within blade or do i need to format the results in my controller first?

CodePudding user response:

You can grouping the list with php (in controller of blade into @php directive):

$list = [];
foreach($services as $item) {
  $list[$item->service_category][] = $item;
}

Updated method

public function order_services(){
    

    $services=  DB::table('services')
            ->selectRaw('id,service_name,service_category,service_price')
            ->orderBy('service_category')
            ->get();
            
    $list = [];
    foreach($services as $item) {
      $list[$item->service_category][] = $item;
    }
    
    return view('guests/services',['list'=>$list]);

}

And you can use $list in blade for display the result:

@foreach ($list as $category => $item)
  <h2>{{ $category }}</h2>
   <ul  id="myUl">
     @foreach ($item as $service)
       <li ><span  style="font-size:24px; color:red
      "><i ></i></span> <span style="font-weight:bold" id="service_category">{{ $service->service_category }}</span><span><u><i ></i></u></span></li>
       <li ><span  style="font-size:24px; color:#870FD1" data-price="349.34"><i ></i></span> <span  id="service_name" data-price="{{ $service->service_price }}" data-category="{{ $service->service_category }}" >{{ $service->service_name }}</span><span ><u>Available</u></span></li>
     @endforeach
   </ul>
@endforeach
  • Related