Reputation: 373
I am getting users and their points, I order them by points and paginate. Now I want to add a number row to result, so first placed user would have num. row 1, second 2 etc.
Currently I have this:
$scores=DB::table('scores')->join('users', 'users.id', '=', 'scores.user_id')
->join('sports', 'sports.id', '=', 'scores.sport_id')
->join('leagues', 'leagues.id', '=', 'scores.league_id')
->select('users.username','points','sports.sportName','leagues.leagueName')
->orderBy($request->sort, $request->direction)->paginate(4);
return json_encode($scores);
EDIT: I am using vue-tables 2 so after API return table is created automatically and I can't print row number with foreach. Expected result would be:
Num. Username Points
1 test2 55
2 test5 42
3 test1 25
4 test4 5
JSON result:
{"data":[
{"num":"1","username":"test2","points":22},
{"num":"2","username":"test1","points":13},
{"num":"3","username":"test4","points":12}
]
}
Upvotes: 1
Views: 3349
Reputation: 25906
Use a foreach()
loop:
$num = ($scores->currentPage() - 1) * $scores->perPage() + 1;
foreach($scores as $score) {
$score->num = $num++;
}
Upvotes: 3