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?
Use
Field()
function of mysql (If you are using mysql database) withDB::raw()
of laravel something likeHere's another way to do that.