John
John

Reputation: 81

Laravel monthly count record

I want to create monthly statistics using Chartjs by Laravel.

$monthly_uploaded_product = DB::table('author_product')
         ->select(DB::raw('count(id) as total'), DB::raw('MONTH(created_at) as month'))
         ->groupBy('month')
         ->get();

the result of query is:

[{"total":1,"month":10},{"total":17,"month":11}]

the output of code should be like this to be represented in Javascript (Chartjs):

[0,0,0,0,0,0,0,0,0,1,17,0]

I have wrote code to generate the array, but error Undefined offset: 1 :

$statistics_monthly_product = array();   
foreach (range(1, 12) as $month) {
    foreach ($monthly_uploaded_product as $key) {
        if ($statistics_monthly_product[$month] == $key->month){
            $statistics_monthly_product[$month] = $key->total;
        }else{
            $statistics_monthly_product[$month] = 0;
        }
    }
}

Upvotes: 2

Views: 1843

Answers (3)

Teun
Teun

Reputation: 926

The line $statistics_monthly_product = array(); creates a new array. Meaning that when you loop later on and try to do $statistics_monthly_product[$month] you are trying to access the index $month of an empty array. This will always give you the error of undefined index, since there is nothing in the array at all.

Perhaps you can initialize the array first with some default values:

$statistics_monthly_product = [0,0,0,0,0,0,0,0,0,0,0,0];

Upvotes: 0

DamianImrich
DamianImrich

Reputation: 44

This code returns your expected array

$data = [["total" => 1,"month" => 10],["total" => 17,"month" => 11]]; 
$monthTotals = [];

foreach($data as $item){
    $monthTotals[$item["month"]] = $item["total"];
}

$chartJSCompat = [];
for($i = 0;$i < 12;$i++){
    if(isset($monthTotals[$i+1]))
        $chartJSCompat[$i] = $monthTotals[$i+1];
    else
        $chartJSCompat[$i] = 0;
}

var_dump($chartJSCompat);

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

You can try something like this:

$year = [0,0,0,0,0,0,0,0,0,0,0,0];//initialize all months to 0

foreach($monthly_uploaded_product as $key)
   $year[$key->month-1] = $key->total;//update each month with the total value
}

Upvotes: 2

Related Questions