I am trying to give my users a ranking number for my Laravel hiscores pagination table.
This is the MySQL query I found working. I am trying to put make this work as a Laravel eloquent query.
select @i := @i + 1 ranking, t.* from (select @i:=0) initvars, users t ORDER BY wins DESC;
My Laravel eloquent query right now:
$ranking = User::orderBy('wins', 'DESC')->paginate(10);
Advertisement
Answer
This is my solution.
I first added this function to my User Modal Class.
public function getRanking(){ $collection = collect(User::orderBy('wins', 'DESC')->get()); $data = $collection->where('id', $this->id); $value = $data->keys()->first() + 1; return $value; }
Now in my view I run my getRanking() function.
@foreach($ranking as $key => $rankings) <tr> <td>{{ $rankings->getRanking() }}</td> <td><a href="{{ route('profileView', ['id' => $rankings->id]) }}">{{ $rankings->username }}</a></td> <td>{{ $rankings->wins }}</td> <td>{{ $rankings->losses }}</td> </tr> @endforeach
I am using my array keys to determine the user ranking.