Laravel Collection Groupby Method Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

2781

15-01-2020


Hi Guys,

In this article, I will explain how you can use Laravel collection in groupBy a method. The groupBy method is used to group a collection based on a given value, represented by the $groupBy parameter. An argument passed to $groupBy can be a simple string, representing the value that the collection should be grouped by, or a callback that returns the value the collection should be grouped by.

The groupBy method does not preserve the keys of the collection when grouping, but that can be changed by passing true as the argument to the $preserveKeys parameter.The groupBy returns a new instance of the Collection class.

The following collection will be used throughout this section when demonstrating the groupBy method:

Example 1

The groupBy method groups the collection's items by a given key:

/**

* Show the application dashboard.

*

* @return \Illuminate\Contracts\Support\Renderable

*/

public function index(){

$collection = collect([

['user_id' => '1', 'name' => 'xyz','impression'=>'10'],

['user_id' => '1', 'name' => 'adc','impression'=>'65'],

['user_id' => '2', 'name' => 'pdc','impression'=>'30'],

]);

$grouped = $collection->groupBy('user_id');

$grouped = $grouped->toarray();

dd($grouped);

}

output

The above $grouped variable will now have a value similar to the following output:

array:2 [?

1 => array:2 [?

0 => array:3 [?

"user_id" => "1"

"name" => "xyz"

"impression" => "10"

]

1 => array:3 [?

"user_id" => "1"

"name" => "adc"

"impression" => "65"

]

]

2 => array:1 [?

0 => array:3 [?

"user_id" => "2"

"name" => "pdc"

"impression" => "30"

]

]

]

Example 2

Instead of passing a string key, you may pass a callback. The callback should return the value you wish to key the group by

/**

* Show the application dashboard.

*

* @return \Illuminate\Contracts\Support\Renderable

*/

public function index(){

$collection = collect([

['user_id' => '1', 'name' => 'xyz','impression'=>'10'],

['user_id' => '1', 'name' => 'adc','impression'=>'65'],

['user_id' => '2', 'name' => 'pdc','impression'=>'30'],

]);

$grouped = $collection->groupBy(function ($item, $key) {

return substr($item['name'], -2);

});

$grouped = $grouped->toarray();

dd($grouped);

}

output

The above $grouped variable will now have a value similar to the following output:

array:2 [▼

"yz" => array:1 [▼

0 => array:3 [▼

"user_id" => "1"

"name" => "xyz"

"impression" => "10"

]

]

"dc" => array:2 [▼

0 => array:3 [▼

"user_id" => "1"

"name" => "adc"

"impression" => "65"

]

1 => array:3 [▼

"user_id" => "2"

"name" => "pdc"

"impression" => "30"

]

]

]

It will help you...


Recommended Posts