Laravel Carbon Group by Month
You can use groupBy()
method with closure:
$months = NewsItem::groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m');
})->get();
Or get data first and then use groupBy()
on the Eloquent collection:
$months = NewsItem::get()->groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m');
});
Why do you need the group by clause in your usecase?
You are not fetching any additional data for which a group by is required, you just want to have a list of distinct months, so use distinct.
$months = NewsItem::selectRaw("MONTH(created_at) as month")->distinct()->get();
Also looking at the solution provided by Alexey, you'll need to fetch the entire dataset from the DB, which is highly inefficient looking at what you are trying to do. A distinct()
query would be much faster than a select *
and group the results in PHP.
Edit:
Little sidenote here, the reason you get null
returned as value is because you use a string in the MONTH()
function instead of the actual field.