Skip to content

Instantly share code, notes, and snippets.

@febridev
Created April 3, 2017 16:18
Show Gist options
  • Save febridev/8b79ca06ed5923cd8d5f09ee10d83fdf to your computer and use it in GitHub Desktop.
Save febridev/8b79ca06ed5923cd8d5f09ee10d83fdf to your computer and use it in GitHub Desktop.
eloquent laravel group by year
// Carbon
use Carbon\Carbon;
$visitorTraffic = PageView::select('id', 'title', 'created_at')
->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y'); // grouping by years
//return Carbon::parse($date->created_at)->format('m'); // grouping by months
});
@abdo-host
Copy link

how to group by year and her months

@theinizio
Copy link

// Carbon
use Carbon\Carbon;
$visitorTraffic = PageView::select('id', 'title', 'created_at')
->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y-m'); // grouping by years and its month
});

@abdo-host
Copy link

Thank you @theinizio
bu i mean years and his months as child array

@theinizio
Copy link

// Carbon
use Carbon\Carbon;
$visitorTraffic = PageView::select('id', 'title', 'created_at')
->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y'); // grouping by years
})->map(function($traffic){
return $traffic->groupBy(function($date){
return Carbon::parse($date->created_at)->format('m'); // grouping by years
});
});

@sajidfrommerqata
Copy link

@theinizio thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment