Search code examples
phplaraveleloquentlaravel-8average

Laravel average of numbers per group


For my project, I want students to see the average grade per school subject.

$grades = Auth::user()->student->grades()
    ->with('subject')->orderByDesc('created_at')
    ->get()->groupBy('subject_id');

Now I first get the grades with the subject and then group them by subject. How can I add the average grade per subject group?

Table columns

enter image description here


Solution

  • The simplest would be to select all rows with subject id X, loop through and and add all the scores to a total, then divide that total by the count() of the rows returned.

    A nicer way might be through crafting a cool SQL query that does the same, but that's for you to decide, this is roughly how you do it.