Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

farshadf's avatar

how to add an auto increment field in laravel api resource

i want to make a ranking for my users based on thier point and what i want to do is to order them by points and set a ranking field to it . i am using laravel api resource and in resource i want to add a field called ranking and ++ it so by the order user be ranked from 0 to n

   $data = User::with('city')
                    ->withCount('point')
                    ->orderByDesc('points_count')
                    ->get()
        ;
        $data = $data->where('points_count', '!=', 0);
        return UserPointResource::collection($data);

and here is my resource :

 return [
            "id"       => (int)$this->id,
            "fullname" => $this->fullname,
            "city"     => $city ? $city->name,
            "count"    => (int)$this->points_count,
        ];

so i want to add a field under count in resource named ranking to ++ each time it shows a user and shows user ranking . thanks

0 likes
1 reply
bobbybouwmann's avatar

You can probably do something like this

$data = User::with('city')
    ->withCount('point')
    ->orderByDesc('points_count')
    ->get();

$data = $data->where('points_count', '>' 0);

$data->map(function ($user, $key) { 
    $user->ranking = $key + 1;
    
    return $user;
});

Documentation: https://laravel.com/docs/7.x/collections#method-map

In your resource, you should have the extra key available now

return [
    // Other fields

    'ranking' => $this->ranking,
];

Please or to participate in this conversation.