Grouping and Counting data from part of id in laravel

26 views Asked by At

I have data like this :

TSAB001001 TSAB001002 TSAB001003 TSAB002001 TSAB002002 TSAB002003 TSIB001001 TSIB001002 TSIB001003 TSIB002001 TSIB002002 TSIB002003

I want to display it in blade :

  • TSA
    • BOO1
      • TSAB001001
      • TSAB001002
      • TSAB001003 Count: 3
    • B002
      • TSAB002001
      • TSAB002002
      • TSAB002003 Count: 3
  • TSI
    • BOO1
      • TSIB001001
      • TSIB001002
      • TSIB001003 Count: 3
    • B002
      • TSIB002001
      • TSIB002002
      • TSIB002003 Count: 3

Can you please help me how to imlementation this in laravel controller and view ?

1

There are 1 answers

0
rizqyhi On

You can use Laravel's Collection map and groupBy methods. First, we need to process the data so that we have a clear data structure to work with:

$data = collect([
    'TSAB001001',
    'TSAB001002',
    'TSAB001003',
    'TSAB002001',
    'TSAB002002',
    'TSAB002003',
    'TSIB001001',
    'TSIB001002',
    'TSIB001003',
    'TSIB002001',
    'TSIB002002',
    'TSIB002003'
])
// Iterate every value above to prepare the base data we need to group
->map(fn ($item) => [
    'value' => $item,
    'prefix' => substr($item, 0, 3),
    'subprefix' => substr($item, 3, 4)
])
// Group for first level prefix
->groupBy('prefix')
// Iterate each group above then group by the subprefix
->map(function ($item) {
    return $item->groupBy('subprefix');
});

Then we can use some nested loop to output the data:

<ul>
  @foreach($data as $prefix => $subprefixes)
    <li>
      {{ $prefix }}
      <ul>
        @foreach($subprefixes as $subprefix => $items)
          <li>
            {{ $subprefix }}
            <ul>
              @foreach($items as $item)
                <li>
                  {{ $item['value'] }}
                  @if($loop->last)
                    Count: {{ count($items) }}
                  @endif
                </li>
              @endforeach
            </ul>
          </li>
        @endforeach
      </ul>
    </li>
  @endforeach
</ul>

We can use special $loop variable inside a blade loop to do some helpful things, like checking if it was the last item ($loop->last).

Learn more from the official docs: