I am listing last 16 days num of views. I want to write 0; if there is not row at date:
$digital_case_daily_views = DB::table('digital_case_views')
->select(DB::raw('count(*) as numOfDigitalCaseViews'))->groupBy('created_at')
->orderBy('created_at', 'desc')->limit(16)->get();
laravel 5.6
it returns like:
"digital_case_daily_views": [
{
"numOfDigitalCaseViews": 162
},
{
"numOfDigitalCaseViews": 458
},
{
"numOfDigitalCaseViews": 287
},
{
"numOfDigitalCaseViews": 1
},
{
"numOfDigitalCaseViews": 1
},
{
"numOfDigitalCaseViews": 1
}
you can't get more rows from the database than available, if you want to have 0 for the remaining days, you have to add them to the array, I've written a function for you that might help you with this:
class Foo {
static public function addRemainingDays(array $arr, int $amount) {
if(count($arr) === $amount) {
return $arr;
}
for($i = 0; i > $amount - count($arr); i++) {
array_push($arr, (object)["numOfDigitalCaseViews" => 0]);
}
return $arr
}
}