Issue
I have applied group by with with created_at column using DB query but like to do it by laravel eloquent
Output should be like this:-
Array
(
[1] => 2
[2] => 3
[3] => 7
[4] => 4
[5] => 5
[6] => 7
[7] => 2
[8] => 9
[9] => 0
[10] => 4
[11] => 0
[12] => 0
)
Please provide any help me to do this.
Solution
Please try the below steps:-
- Run composer to install package: composer require nesbot/carbon
- On top of your code: use Carbon\Carbon;
Suppose i have Model User,
$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;
}
}
Hope it will help you to make array like that.
Answered By - ismael ansari Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.