I think the problem is this:
When you call User::all() , you get something like this:
0 => points: 10 1 => points: 50 2 => points: 30 3 => points: 70 4 => points: 20
Then you use the sortBy function, which reorders the collection, but does not reset the keys. So you get something like this:
3 => points: 70 1 => points: 50 2 => points: 30 4 => points: 20 0 => points: 10
Thus, the use of position -1, position and position +1 does not make sense here.
What you can do is use the values () function, which will reset the keys of your collection:
0 => points: 70 1 => points: 50 2 => points: 30 3 => points: 20 4 => points: 10
So, I think the following code will work.
$users = User::all(); $users = $users->sortByDesc(function($item){ return $item->points()->sum('amount'); })->values();
And then get 3 users from positions - 1 to position + 1:
$myRank = $users->splice($position - 1, 3);
source share