user5405648
user5405648

Reputation:

Laravel: orderBy find position of user?

I have a page where I list the richest users on my game.

$topCredits = User::orderBy('credits', 'DESC')->limit($limit)->get();

the limit is currently set to 5 and sometimes doesn't show a user if they aren't that rich. I need a way of still showing the user their position (IE: 1st, 2nd, 9th, 24th) but also showing the top 5. I was wondering is there a way I can do this without an extra query, or how would I do it with an extra query? Finding a certain user in a list of User models?

Upvotes: 1

Views: 273

Answers (2)

Jacobo
Jacobo

Reputation: 1391

Once I had to do something similar. I just create an iterator @foreach ($users as $index => $user) so then to know the position you’ll only {{ $index+1 }}

Upvotes: 1

Mahdi Younesi
Mahdi Younesi

Reputation: 7489

Use Laravel take helper

$credits = User::orderBy('credits', 'DESC')->get();

$topFiveCredits =  $credits->take(5);

Upvotes: 0

Related Questions