Home > Net >  Laravel does not give the values sequentially
Laravel does not give the values sequentially

Time:11-26

I have a car ids array.

$carIds = [21,12,33];

I'm sending an ids array to retrieve values from my collection.

$cars = Cars::whereIn('id', $carIds)->get();

Incoming car values do not come in the order of id I gave, it is complicated.

CodePudding user response:

update your code with below code

Cars::whereIn('id', $carIds)
->orderByRaw('FIELD (id, ' . implode(', ', $carIds) . ') ASC')
->get();

CodePudding user response:

Different way you can do is :

$cars = DB::table('Cars')
                ->orderBy('id', 'desc')
                ->get();
  • Related