Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

leonardharley's avatar

Group by date within date range and average value

I have a fuel tank levels table that holds hourly level readings. In order to graph these levels over long periods I need to get the average of the volume recorded between a given date range.

The following works perfectly to group the hourly level readings by day:

$levels = TankLevel::where('tank_id', '=', $tank->id)
                ->where('level_date', '>', $start_date->format('Y-m-d H:i'))
                ->where('level_date', '<', $end_date->format('Y-m-d H:i'))
                ->get()
                ->groupBy(function($date) use ($site) {
                return Carbon::parse($date->level_date)->setTimezone($site->site_timezone->timezone)->format('d'); }) ;

What I'm struggling with is how to add ->ave('volume') into the mix so that I get a results set that is grouped by day (or month, or year) AND which aggregates the volume value as an average. I'm not sure if what I'm trying to do is even possible. Any help would be much appreciated.

0 likes
1 reply

Please or to participate in this conversation.