Perform average in array in Laravel

I'm trying to calculate an average in my table. The column name is term1_result and the average is in the array since my table has many students and subjects. I group them by student_id, but I always end up getting a zero value. I'm using the Laravel framework.

Code

$scores = Grades::with('student', 'subject')->groupBy('student_id')->get();

foreach($scores as $score) {
    foreach($score as $key => $value) {
        $sum_arr[] = $value['term1_result'];
    }
    $avg = array_sum($sum_arr) / count($sum_arr);
    $avgarr[] = $avg;
}

dd($avgarr);

Result

array:6 [▼
  0 => 0
  1 => 0
  2 => 0
  3 => 0
  4 => 0
  5 => 0
]

2 answers

  • answered 2019-01-11 05:25 Hamed Zarei

    This is because of your SQL content!

    Have you dump your scores to see result?

    You must sum over each items in each groups.

    You can see this to learn more

  • answered 2019-01-11 05:38 user10940762

    You should try this:

    $scores = Grades::with('student','subject')->groupBy('student_id')->avg('term1_result');