Skip to content
Advertisement

Laravel Carbon Group by Month

Can anyone see what I’m doing wrong?

I’m trying to output all the months but group them so they are unique.

$months = NewsItem::select(DB::raw('MONTH("created_at") as month'))->groupBy('month')->get();
return $months;

I’m getting the following back

{"month":null}

In my database I have five news articles all created_at 05/01/2017 so it’s right that I only get one response but I’m not getting the number of the month back?

Advertisement

Answer

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');
 });
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement