groupBy() Method Laravel Collection Exmaple

  • 17-05-2022
  • 1515
  • Laravel 9
  • Haresh Chauhan

What is groupBy() in Laravel?

The groupBy() method in laravel returns the query result by grouping the data collection and returns the query result from the database table or collection result.

Suppose you have multiple data with the same type of name or age, if you want to group the data by name or age the laravel groupBy() method will help you the differentiate it.

It will remove duplicate values from the data collection and make its unique collection. which you want to group the type.

It will specify the type of data without any duplicate value in the data.

Laravel groupBy() method is grouping the collection of an item the key name you pass in the params.

With grouping you can use groups of raw with count(), min(), max(), avg(), sum(), orderBy().

When we working with large data at that time we were required to handle it through various methods. So today in this post we are going to learn how to create a laravel collection data using the laravel groupBy() method.

The groupby() method is grouping the query result in laravel collection of data it allows you to group the data by particular data.

So lets you assume that you have 100 record that is like users on the post, but you need to count the post likes so here users may like multiple time on the same post. so in this case we need to take make of groupby()method for counts like's of user each post and unique users.

Example 1: User Simple groupBy() Method

This simple example says groupby() of product, so you can see that output mobile has two collections that's the duplicate record in product.

$data = [
    ['product' => 'mobile', 'price' => 10000],
    ['product' => 'mobile', 'price' => 10000], // IS DUPLICATE
    ['product' => 'laptop', 'price' => 50000],
    ['product' => 'tablet', 'price' => 21500],
    ['product' => 'LED', 'price' => 15600],
];

$collection = collect($data)->groupBy('product');

// OUTPUT

Illuminate\Support\Collection {#6790 ▼
    #items: array:4 [▼
        "mobile" => Illuminate\Support\Collection {#6785 ▼
            #items: array:2 [▼
                0 => array:2 [▼
                "product" => "mobile"
                "price" => 10000
                ]
                1 => array:2 [▼
                "product" => "mobile"
                "price" => 10000
                ]
            ]
            }
            "laptop" => Illuminate\Support\Collection {#6787 ▼
            #items: array:1 [▼
                0 => array:2 [▼
                "product" => "laptop"
                "price" => 50000
                ]
            ]
            }
            "tablet" => Illuminate\Support\Collection {#6788 ▼
            #items: array:1 [▼
                0 => array:2 [▼
                "product" => "tablet"
                "price" => 21500
                ]
            ]
            }
            "LED" => Illuminate\Support\Collection {#6789 ▼
            #items: array:1 [▼
                0 => array:2 [▼
                "product" => "LED"
                "price" => 15600
            ]
            ]
        }
    ]
}

Example 2: Use With groupBy() Array Key Collection

In this exmaple collection have indexing that's item1, item2, item3, item4 by passing argument groupBy('product',true) that show's you each item indexing in grouping collection.

$data = [
    'item1' => ['product' => 'mobile', 'price' => 10000],
    'item2' => ['product' => 'mobile', 'price' => 10000], // IS DUPLICATE
    'item3' => ['product' => 'laptop', 'price' => 50000],
    'item4' => ['product' => 'tablet', 'price' => 21500],
    'item5' => ['product' => 'LED', 'price' => 15600],
];

// OUTPUT

$collection = collect($data)->groupBy('product',true);

Illuminate\Support\Collection {#6790 ▼
    #items: array:4 [▼
        "mobile" => Illuminate\Support\Collection {#6785 ▼
            #items: array:2 [▼
            "item1" => array:2 [▼
                "product" => "mobile"
                "price" => 10000
            ]
            "item2" => array:2 [▼
                "product" => "mobile"
                "price" => 10000
            ]
            ]
        }
        "laptop" => Illuminate\Support\Collection {#6787 ▼
            #items: array:1 [▼
            "item3" => array:2 [▼
                "product" => "laptop"
                "price" => 50000
            ]
            ]
        }
        "tablet" => Illuminate\Support\Collection {#6788 ▼
            #items: array:1 [▼
            "item4" => array:2 [▼
                "product" => "tablet"
                "price" => 21500
            ]
            ]
        }
        "LED" => Illuminate\Support\Collection {#6789 ▼
            #items: array:1 [▼
            "item5" => array:2 [▼
                "product" => "LED"
                "price" => 15600
            ]
            ]
        }
    ]
}

Example 3: Use groupBy() With Replace The String

This example having product code that is different code with each product item, but I want to understand you that is groupBy() callback replace the item into string ['-',' ','~','-','_'] from given veriation and then group the each item.

$data = [
    ['product_code' => 'PD-10', 'price' => 10000],
    ['product_code' => 'PD 10', 'price' => 10000],
    ['product_code' => 'PD~10', 'price' => 50000],
    ['product_code' => 'PD-10', 'price' => 21500],
    ['product_code' => 'PD_10', 'price' => 15600],
];

$collection = collect($data)->groupBy(function($element){

    return str_replace(['-',' ','~','-','_'],'',$element['product_code']);
});

// OUTPUT

Illuminate\Support\Collection {#6787 ▼
    #items: array:1 [▼
        "PD10" => Illuminate\Support\Collection {#6785 ▼
            #items: array:5 [▼
                0 => array:2 [▼
                "product_code" => "PD-10"
                "price" => 10000
                ]
                1 => array:2 [▼
                "product_code" => "PD 10"
                "price" => 10000
                ]
                2 => array:2 [▼
                "product_code" => "PD~10"
                "price" => 50000
                ]
                3 => array:2 [▼
                "product_code" => "PD-10"
                "price" => 21500
                ]
                4 => array:2 [▼
                "product_code" => "PD_10"
                "price" => 15600
                ]
            ]
        }
    ]
}

Example 4: Use Always groupBy() With New Collection.

And this last example group never returns the data into the same collection, you always need to take it new collection for return collection.

$data = [
    ['product_code' => 'PD-10', 'price' => 10000],
    ['product_code' => 'PD 10', 'price' => 10000],
    ['product_code' => 'PD~10', 'price' => 50000],
    ['product_code' => 'PD-10', 'price' => 21500],
    ['product_code' => 'PD_10', 'price' => 15600],
];

$collection = collect($data);

$newCollection = $collection->groupBy(function($element){
    return str_replace(['-',' ','~','-','_'],'',$element['product_code']);
});

// OUTPUT

Illuminate\Support\Collection {#6787 ▼
    #items: array:1 [▼
        "PD10" => Illuminate\Support\Collection {#6785 ▼
            #items: array:5 [▼
                0 => array:2 [▼
                "product_code" => "PD-10"
                "price" => 10000
                ]
                1 => array:2 [▼
                "product_code" => "PD 10"
                "price" => 10000
                ]
                2 => array:2 [▼
                "product_code" => "PD~10"
                "price" => 50000
                ]
                3 => array:2 [▼
                "product_code" => "PD-10"
                "price" => 21500
                ]
                4 => array:2 [▼
                "product_code" => "PD_10"
                "price" => 15600
                ]
            ]
        }
    ]
}

Laravel eloquent groupBy() also returns the count of each group of an item and the count you make it ordered the value.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :