Home  >  Q&A  >  body text

How to achieve similar functionality using foreach and group in Laravel's Blade template?

I am retrieving tracking data from DHL API and the data I am getting is as follows: Data from DHL Tracking API

I use foreach in laravel Blade, the result is this: Foreach

on the blade

How to create a foreach group in Laravel Blade as follows: View on DHL website

Please help, thank you.

P粉106301763P粉106301763211 days ago380

reply all(2)I'll reply

  • P粉237125700

    P粉2371257002024-02-26 14:34:16

    Personally, I would do it all in the controller. Access the api with only the information you need (which looks like more information than you actually need), process that data in the controller and build your own collection, sort and group that data, and send to the frontend. Keep the logic in the controller.

    reply
    0
  • P粉715228019

    P粉7152280192024-02-26 00:34:15

    You can use Laravel's collections to group results from the API by date.

    @php
        $groupedResult = collect([$apiResult])->groupBy(function($item) {
                          return Carbon::parse($item['timestamp'])->format('Y-m-d');
                      });
    @endphp
    
    @foreach($groupedResult as $date => $row)
     {{ $date }}
     @foreach($row as $item)
       // each day's transactions
     @endforeach
    @endforeach

    But I recommend processing the data in the controller and then sending it to the front end.

    reply
    0
  • Cancelreply