how to get every month wise data in laravel code example

Example: get all users created in a month laravel

$users = User::select('id', '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
});

$usermcount = [];
$userArr = [];

foreach ($users as $key => $value) {
    $usermcount[(int)$key] = count($value);
}

for($i = 1; $i <= 12; $i++){
    if(!empty($usermcount[$i])){
        $userArr[$i] = $usermcount[$i];    
    }else{
        $userArr[$i] = 0;    
    }
}

Tags:

Php Example