BenNov BenNov - 1 year ago 53
MySQL Question

PHP - Laravel - Getting average directly from Eloquent and not having to loop through the results

I'm building a survey platform and I need to get the average answer rate of the survey.
What I'm currently doing is retrieving all the questions and then dividing times viewed and times answered. Is there a more efficient / less resource consuming method by calculating average on the DB and not looping through thousands of results?

Here is my working code right now that takes forever:

$total_showed = 0;
$total_answered = 0;

$total_queries = Query::where('client_app_id','=', $app_id)->get();

foreach ($total_queries as $app_query) {
$total_showed = $total_showed + $app_query->showed;
$total_answered = $total_answered + $app_query->answered;
if ($total_showed > 0) {
$total_arate = round(($total_answered / $total_showed) * 100, 1);
} else {
$total_arate = 0;

Answer Source

try $total_showed = $total_queries->sum('showed') $total_answered = $total_queries->sum('answered')

since $total_queries is a collection you can use it's sum method see this would be mre efficient I think