Refactoring to collections, groupby, map and sum Collections are very powerful, here we show the power of groupby, map and sum in one line https://laravel.com/docs/8.x/collections
requires: laravel 5.1

In this code we need to show the total price of and offers lines, grouped by the group the lines are in. This refactor makes it a one-liner 🔥

Original code



        /*
         *  $offer = [
                'name'  => 'offer1',
                'lines' => [
                    ['group' => 1, 'price' => 10],
                    ['group' => 1, 'price' => 20],
                    ['group' => 2, 'price' => 30],
                    ['group' => 2, 'price' => 40],
                    ['group' => 3, 'price' => 50],
                    ['group' => 3, 'price' => 60]
                ]
             ];
         */

        $offer $this->getOffer();

        
$totalPerGroup = [];
        if (
count($offer->lines) > 0) {
            foreach (
$offer->lines as $line) {
                if (isset(
$totalPerGroup[$line->group])) {
                    
$totalPerGroup[$line->group] += $line->price;
                } else {
                    
$totalPerGroup[$line->group] = $line->price;
                }
            }
        }
        

Refactored code



        /*
         *  $offer = [
                'name'  => 'offer1',
                'lines' => [
                    ['group' => 1, 'price' => 10],
                    ['group' => 1, 'price' => 20],
                    ['group' => 2, 'price' => 30],
                    ['group' => 2, 'price' => 40],
                    ['group' => 3, 'price' => 50],
                    ['group' => 3, 'price' => 60]
                ]
             ];
         */

        $offer         $this->getOffer();
        
$totalPerGroup collect($offer->lines)->groupBy('group')->map(fn($group) => $group->sum('price'));

        

Here is the output of the code

This is the output of original

{"1":30,"2":70,"3":110}

This is the output of refactor

{"1":30,"2":70,"3":110}

Want to learn more from LLoadout ?

LLoadout is your loadout for Laravel, helping you kickstart your development process. Besides this refactoring site we also make some cool packages and video tutorials !

Go to LLoadout on github