Hi everyone, I have the collection below and I want to compute the average of all uptimes with the type API group by every day, how can I do that? I fetched all data from the table first, and I want to do calculations on it with the help of eloquent, I do not want to get average at first, I mean I want to find every day average uptime of API types. is there a good way to do so?
thank you all,
To compute the average of all uptimes with the type API group by every day, you can use the groupBy() and avg() methods in Eloquent. Here's an example:
$apiUptimes = ChartData::where('type', 'API')
->selectRaw('DATE(date) as date, AVG(uptime) as avg_uptime')
->groupBy('date')
->get();
foreach ($apiUptimes as $apiUptime) {
echo "On " . $apiUptime->date . ", the average uptime was " . $apiUptime->avg_uptime . "% for API type.\n";
}
This code will retrieve all the ChartData records with the type API, group them by date, and calculate the average uptime for each day. The resulting collection will contain objects with two properties: date and avg_uptime. You can then loop through the collection and display the results as desired.