John Davidson

php - Grouping items of the same category type in blade

0 comments
Message:


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 class="list-group" id="myUl">
@foreach ($services as $service)
<li class="list-group-item d-flex justify-content-between align-items-center border border-danger"><span style="font-size:24px; color:red
"><i class="bi bi-check-circle font-weight-bold "></i></span> <span style="font-weight:bold" id="service_category">{{ $service->service_category }}</span><span><u><i class="bi bi-magic"></i></u></span></li>
<li class="list-group-item d-flex justify-content-between align-items-center"><span class="product_name" style="font-size:24px; color:#870FD1" data-price="349.34"><i class="bi bi-plus-circle"></i></span> <span class="product_name" id="service_name" data-price="{{ $service->service_price }}" data-category="{{ $service->service_category }}" >{{ $service->service_name }}</span><span class="text-success"><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?



My Answer:
You can achieve this grouping within Blade by first sorting your services array by service_category and then using a conditional statement to check if the current service_category is different from the previous one. If it is different, you can display a new header for that category.

Here's an example of how you can modify your Blade code to achieve this:

html

    @php
    $prevCategory = null;
    @endphp
    @foreach ($services as $service)
    @if ($service->service_category != $prevCategory)

    {{ $service->service_category }}


    @php
    $prevCategory = $service->service_category;
    @endphp
    @endif




  • {{ $service->service_category }}







  • {{ $service->service_name }}

    Available

  • @endforeach



This code will check if the current service_category is different from the previous one and display a new header for that category. This way, all services under the same category will be grouped together.

Rate this post

3 of 5 based on 8210 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us