Chartjs-Return 0 as data for months with no data

0👍

Below (pseudo) code uses the power off the Laravel collection.
I suggest you read through the docs of Laravel on collections: https://laravel.com/docs/7.x/collections#method-first-where

// Your original query slightly altered (pay attention to the toArray being removed)
// $models = ModelName::select(
//   DB::raw('count(id) as count'), 
//   DB::raw("MONTH(created_at)  as month")
// ) 
//     ->where('org_id', auth()->user()->org_id)
//     ->where('result_code', 200)
//     ->groupBy('month')
//     ->orderBy('month')
//     ->get();

// $models is now resembles your result from the above.
$models = collect([
  ['count' => 1, 'month' => 1],
  ['count' => 10, 'month' => 3],
  ['count' => 1, 'month' => 5],
  ['count' => 15, 'month' => 7],
  ['count' => 1, 'month' => 9],
  ['count' => 25, 'month' => 11],
]);

$months = collect(range(1, 12))->map(
  function ($month) use ($models) {
    $match = $models->firstWhere('month', $month);
    return $match ? $match['count'] : 0;
  }
);

Result of $months

=> Illuminate\Support\Collection {#1046
     all: [
       1,
       0,
       10,
       0,
       1,
       0,
       15,
       0,
       1,
       0,
       25,
       0,
     ],
   }

0👍

Though it is not tested personally by me but as per documentation. In your model you can do attribute casting.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ModelName extends Model
{
    
    protected $casts = [
        'count' => 'integer',
    ];
}

So now, count attribute will always be cast to a integer when you access it, even if the underlying value is stored in the database as null.
Also we know that if we typecast null value to integer it will return 0.
eg $n = null; echo (int)$n; // answer is 0

Note: It might be correct, so if it didn’t work please tell in the comments.

Leave a comment