Support the ongoing development of Laravel.io →
Eloquent Database Blade

Basically I have a point log table as follows:

user_id | points
1       | 10
2       | 20
1       | 30
1       | 4
2       | 6
6       | 8

and I am looking to group the users by their total points and display their ranking.

This is what I have so far in my User.php model:

public function getPointRankAttribute() {
  return $this->hasMany('App\PointLog')->select(DB::raw('
          SELECT s.*, @rank := @rank + 1 rank FROM (
            SELECT user_id, sum(points) TotalPoints FROM t
            GROUP BY user_id
          ) s, (SELECT @rank := 0) init
          ORDER BY TotalPoints DESC
        ')
    );
}

and then display in my blade template as follows:

Your point rank: {{ $user->pointRank }}
Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

tpx tpx Joined 3 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.