Thursday, April 13, 2017

Show post counts for every day of week in laravel

I have a function in my controller with this:

$one_week_ago = Carbon::now()->subDays(6)->format('Y-m-d');
$dates = Post::where('created_at', '>=', $one_week_ago)
        ->groupBy('date')
        ->orderBy('date', 'ASC')
        ->get(array(
             DB::raw('Date(created_at) as date'),
             DB::raw('COUNT(*) as "count"')
          ));

return view ('analytics', array('dates' => $dates));

And my view is:

@foreach ($dates as $date => $count) 
      <p> </p>
@endforeach

I am getting the output as:

0 - {"date":"2017-04-07","count"->7}

1 - {"date":"2017-04-08","count"->2}

2 - {"date":"2017-04-12","count"->4}

3 - {"date":"2017-04-13","count"->1}

Problem: The dates in which there were no posts (posts count-> 0) those are not shown. Example: 2017-04-09, 2017-04-10 and 2017-04-11 are not shown.

But I want the output for those dates as count->0

Also how to convert this to plain string, as the output is in array?



via thehackwall

Advertisement