0

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.

  • 1
    Because default sorting in database is done by id. You will have to sort to the wanted order manually. – Adrian Kokot Nov 26 '21 at 09:59
  • Does this answer your question? [Maintaining order in MySQL "IN" query](https://stackoverflow.com/questions/1631723/maintaining-order-in-mysql-in-query) – ManojKiran A Nov 26 '21 at 13:46

2 Answers2

0

update your code with below code

Cars::whereIn('id', $carIds)
->orderByRaw('FIELD (id, ' . implode(', ', $carIds) . ') ASC')
->get();
yadu siva das
  • 517
  • 3
  • 12
0

Different way you can do is :

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