8

I have an array of product ids against which I need to retrieve the model collection. The array is something like this:

$ids = array(9, 2, 16, 11, 8, 1, 18);

Right now, I'm using the following line of code to get the collection.

$products = Product::whereIn('id', $ids)->get();

But it sorts the products against their ids. such as: 1, 2, 8, 9, 11, 16, 18. What I need is the same order as in the $ids array i.e 9, 2, 16, 11, 8, 1, 18.

What should I do to get the same order as in the array?

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
Ahmed Raza
  • 294
  • 4
  • 18
  • It's an interesting question. I'd say that's more of a custom sort than unsorted, though. – Don't Panic Nov 13 '17 at 18:01
  • 1
    I think I found a duplicate for it based on that: https://stackoverflow.com/questions/40731863/sort-collection-by-custom-order-in-eloquent – Don't Panic Nov 13 '17 at 18:02
  • I don't want to close your question as duplicate of that one yet because I'm not 100% sure that's what you want. Does the answer there solve your problem? – Don't Panic Nov 13 '17 at 18:04
  • 1
    I believe the duplicate candidate answers the question. However, Khalid's answer on this one is much more interesting. @Don'tPanic – sepehr Nov 13 '17 at 18:12
  • Yes, the linked solution is great and working. Thanks a lot. – Ahmed Raza Nov 13 '17 at 18:15

2 Answers2

11

Use Field() function of mysql (If you are using mysql database) with DB::raw() of laravel something like

$products = Product::whereIn('id', $ids)
    ->orderBy(DB::raw("FIELD(id,".join(',',$ids).")"))
    ->get();

Field() returns the index position of a comma-delimited list

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
2

Here's another way to do that.

$ids = array(9, 2, 16, 11, 8, 1, 18);
$products = User::whereIn('id', $ids)->orderByRaw('FIELD(id, '.implode(',', $ids).')')->get();
Suraj
  • 2,181
  • 2
  • 17
  • 25