This is my code where I am getting country ranking on corruption by get request
public function getByYear($year)
{
return $this->safeCall(function () use ($year) {
$rankings = CorruptionRanking::where('year', $year)
->orderBy('points', 'desc')
->get();
if ($rankings->isEmpty()) {
return $this->errorResponse('No data found for the given year', 404);
}
$rank = 1;
$rankings->each(function ($ranking, $index) use (&$rank, $rankings) {
if ($index > 0 && $ranking->points === $rankings[$index - 1]->points) {
$ranking->rank = $rank -1;
} else {
$ranking->rank = $rank;
$rank++;
}
$ranking->save();
});
return $this->successResponse('Rankings retrieved successfully', [
'year' => $year,
'rankings' => $rankings
]);
});
}
And this is my output
"rankings": [
{
"id": 1541,
"country_name": "Denmark",
"year": 2017,
"points": 8.8,
"rank": 1,
"created_at": "2025-04-17T11:41:36.000000Z",
"updated_at": "2025-04-19T05:37:40.000000Z"
},
{
"id": 1886,
"country_name": "Finland",
"year": 2017,
"points": 8.5,
"rank": 2,
"created_at": "2025-04-17T11:41:36.000000Z",
"updated_at": "2025-04-19T05:38:37.000000Z"
},
{
"id": 3680,
"country_name": "Norway",
"year": 2017,
"points": 8.5,
"rank": 2,
"created_at": "2025-04-17T11:41:38.000000Z",
"updated_at": "2025-04-19T05:38:37.000000Z"
},
{
"id": 4715,
"country_name": "Switzerland",
"year": 2017,
"points": 8.5,
"rank": 2,
"created_at": "2025-04-17T11:41:39.000000Z",
"updated_at": "2025-04-19T05:38:37.000000Z"
},
{
"id": 4370,
"country_name": "Singapore",
"year": 2017,
"points": 8.4,
"rank": 3,
"created_at": "2025-04-17T11:41:39.000000Z",
"updated_at": "2025-04-19T05:38:37.000000Z"
},
But i am expecting output where Denmark rank 1 its good and Finland,Norway,Switzerland rank 2 is also good But Singapore,Sweden should be rank 5 and this will follow the ranking sequence thanks