Getting daily aggregates/sum sorted by day in Laravel

Kylie picture Kylie · May 27, 2013 · Viewed 7.2k times · Source

So getting a sum()/count() is really easy in Laravel... but how would I look at the past month, and get the sum of rows every day?

EG...grouped by day that they were created at.

So I want to return a count such as 3, 2, 4, 5 Meaning 3 rows were created on todays date, 2 rows yesterday, 4 rows the day before...etc

How to do this in Laravel easily? When I use the group by created_at it always just returns 1.

Anybody know how to do it?

Thanks

Answer

vFragosop picture vFragosop · May 27, 2013

I've provided the same answer on another post. Shortening it:

$date = new DateTime('tomorrow -1 month');

// lists() does not accept raw queries,
// so you have to specify the SELECT clause
$days = Object::select(array(
        DB::raw('DATE(`created_at`) as `date`'),
        DB::raw('COUNT(*) as `count`')
    ))
    ->where('created_at', '>', $date)
    ->group_by('date')
    ->order_by('date', 'DESC')
    ->lists('count', 'date');

// Notice lists returns an associative array with its second and
// optional param as the key, and the first param as the value
foreach ($days as $date => $count) {
    print($date . ' - ' . $count);
}