PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

[FIXED] How to get all month record count in laravel

 May 16, 2022     laravel-5, mysql, php     No comments   

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:-

  1. Run composer to install package: composer require nesbot/carbon
  2. 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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing