Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Bezara's avatar

How to get rank student using laravel

I'm trying to get the rank of the student using the total marks, i.e. the student with higher marks than the other should be first and so on. Then when two or more students have the same total marks, they should have the same rank, help me. I have two tables. 1- table - students:

id  name    class_id created_at
1   Emma     1    
2   Frank    3    
3   Bright   4    
4   Doe      1   

2- table - marks:

id id_student  class_id  subject_id  mark   created_at
1   2           3         2          115 
2   4           1         1          120
3   3           4         4          90

I want to get the rank for student the highly mark. How to make it please.

0 likes
7 replies
Snapey's avatar

do students have more than one class?

2 likes
Bezara's avatar

@Snapey Thank you for your reply, Students have different classes. For example: the 1st class has 10 students and the 2nd has 20 students

Bezara's avatar

I need help, please. someone can help me?

sr57's avatar

@bezara

Seems you don't understand @snapey 's question.

"do students have more than one class?" means what is the usage of class_id in the table marks?

1 like
Snapey's avatar

@sr57 exactly. Is their score per class or does it need to be aggregated across their classes?

1 like
Bezara's avatar

@Snapey Students may have a different class. So, for example, a student in the 1st class is possible to earn a score of 20 in one subject and he earns 40 for another subject,...

achur00's avatar

your requirement is somewhat confusing. But if we proceed with your Table we could have something like this to get the total_score

  $total_score = DB::table('YourTable')->select(DB::raw("SUM(mark) as total"))->where('id_student', '=', 
  $id_student)->get();

you should see the collection you can work with, if you dd($total_score);

1 like

Please or to participate in this conversation.