Hello Devs, 

In this tutorial, we will learn Laravel Collection Groupby Method Example

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.

Follow this step by step guide below. 



Example 1

/**
 * 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:

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

/**
 * 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: 

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"
    ]
  ]
]

May this example help you.