How to get data values from collection using group by on laravel?
To get data values from a collection using groupBy in Laravel, you can follow these steps:
- Fetch the data from the database using query builder or Eloquent ORM and apply any necessary filters or sorting.
- Use the
groupBy
method on the collection to group the data based on a specific column. - Use the
map
ormapWithKeys
method to transform each group into an associative array or a new collection with the desired keys.
Here's an example using Eloquent ORM:
// Fetch data from the database
$data = App\Model::where('status', 'published')
->orderBy('created_at', 'desc')
->get();
// Group the data by a specific column
$groupedData = $data->groupBy('category_id');
// Transform each group into an associative array
$transformedData = $groupedData->map(function ($group) {
return [
'category_id' => $group->first()->category_id,
'category_name' => $group->first()->category->name,
'data' => $group->map(function ($item) {
return [
'id' => $item->id,
'title' => $item->title,
'created_at' => $item->created_at->format('Y-m-d H:i:s'),
];
})->all(),
];
});
// Output the transformed data
dd($transformedData->toArray());
In this example, we first fetch the data from the database using Eloquent ORM and apply some filters and sorting. We then use the groupBy
method to group the data by a specific column (category_id
). Finally, we use the map
method to transform each group into an associative array with the desired keys (category_id
, category_name
, and data
). The data
key contains another collection with the transformed data for that specific group.
You can modify the transformation logic to suit your specific use case.