Reputation: 533
I'm having a LEADERBOARD table with 5 columns in it. I'm able to auto-sort(i.e. top scorer on the top of the table) the table with SCORE(column 5) of a user with a script. but when table auto-sorted the Serial Number(column 1) also altered. I want to use first column to display the RANK of a user so it must be like 1, 2, 3, 4 and so on. But it keep changes as score of a user varies.
Here is the table structure:
<thead>
<tr>
<th>Rank</th>
<th>Gravatar</th>
<th>Name</th>
<th>Branch</th>
<th>Score</th>
</tr>
</thead>
<tbody class="searchable">
@if(count($visitors)>0)
@foreach($visitors as $key=>$visitor)
<tr>
<td>{{$key+1}}</td>
<td><img style="border-radius: 50%" width="50px" height="50px" src="{{ Gravatar::src($visitor->email) }}"></td>
<td>
<a href="/profile/{{$visitor->id}}">
{{$visitor->name}}
</a>
</td>
<td>{{$visitor->branch}}</td>
<td>{{$visitor->rank_score}}</td>
</tr>
@endforeach
@else
<td>No User at this time.</td>
@endif
</tbody>
Here is Script:
$(document).ready(function() {
$('#userTable').DataTable({
"order": [4, 'rank_score'],
});
});
If first column display fix serial number then I can use it to display rank.
Thanks.
Upvotes: 0
Views: 505
Reputation: 277
You are calculating the rank with php in your blade view, by using the key in the for loop. You must first sort your visitors array by the rank score, then display them with the loop. Ideally this is done in your database with an order by clause, or you could do it in your view:
@foreach($visitors->sortByDesc(‘rank_score’)->values() as $key=>$visitor)
The values()
resets the keys after sorting which you need.
With the JavaScript you can then use the rank and the order column (ascending).
Upvotes: 1