Roseanne
Roseanne

Reputation: 77

How to sort from highest to lowest after sum the value in Laravel?

I am new to Laravel. Right now, I am having a difficulty on how to sort students' name from highest to lowest based on their total marks. Below are my data from the Postman.

{ 
  "score": [
    {
        "name": "Adam",
        "sex": "male",
        "totalMarks": 250
    },
    {
        "name": "Lisa",
        "sex": "female",
        "totalMarks": 350
    },
    {
        "name": "Daniel",
        "sex": "male",
        "totalMarks": 300
    },
    {
        "name": "Mary",
        "sex": "female",
        "totalMarks": 330
    },
    {
        "name": "Sarah",
        "sex": "female",
        "totalMarks": 280
    }
  ]
}

Below is my code from ScoreController.php

$class_id = $user->class->id;
$students = Students::whereIn('class_id', $class_id)->get();
$score = array();

foreach ($students as $student) {
   array_push($score, [
      'name' = $student->name,
      'sex' = $student->sex,
      'totalMarks' = $student->subjects->sum('mark'),
   ]);
}

return response()->json([
  'score' => $score,
]);

I would like to sort student based on sum of the mark. So a student with a highest totalMarks should be at the top of the list. Thank you in advance.

Upvotes: 1

Views: 640

Answers (1)

mrhn
mrhn

Reputation: 18926

Using eloquent attributes will probably do you good here. In your Students class add an eloquent mutator.

class Students {
    // to include it in the response.
    $with = ['totalMarks'];

    public function getTotalMarksAttribute() {
        return $this->subjects->sum('mark');
    }
}

Now you can optimize your original code a bit. You don't have to transform your objects into an array, with this approach.

$students = Students::whereIn('class_id', $class_id)
    ->get()
    ->sortByDesc('totalMarks');

// laravel will automatic transform the objects, an way more maintainable approach
return response()->json([
  'score' => $students,
]);

Upvotes: 1

Related Questions