Lucas Decrock
Lucas Decrock

Reputation: 232

Laravel Eloquent - Get a record every hour

I have a table that stores statistics every 3 minutes with a cron job. I want to display a chart with this data but I want the chart to have an interval of 1 hour otherwise it looks ugly as hell and is too much resource demanding. The table has the created_at and updated_at columns.

How can I do this with eloquent?

EDIT: I want to query the records from the last 24 hours but that gives me around 480 records which is too much for a chart. I'd like to have only 24 records instead (one for every hour).

Thanks for your help!

Upvotes: 1

Views: 5849

Answers (2)

Lucas Decrock
Lucas Decrock

Reputation: 232

Thanks Tim! For anyone reading through this later, here is the solution: https://laracasts.com/discuss/channels/laravel/count-rows-grouped-by-hours-of-the-day

Model::where('created_at', '>=', Carbon::now()->subDay())->get()->groupBy(function($date) {
    return Carbon::parse($date->created_at)->format('h');
});

Upvotes: 3

Lim Kean Phang
Lim Kean Phang

Reputation: 501

This will allow you to get data 1 hours ago base on current time.

//Get all data for the day
$all_data = Model::where('created_at','>=',Carbon::today()->get());
//Recursive to groupBy hours
$i=1;
while ($all_data->last() != null)
{
    $hourly_data = Model::where('created_at','>=',Carbon::today()->addHours($i))->get();
    $all_data= $all_data->merge($hourly_data);
$i++
}

return $all_data;

Upvotes: 0

Related Questions