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?
Laravel Sorting a collection 1 Sort () The sort method also allows for passing in a custom callback with your own algorithm. Under the hood sort uses php's usort. 2 SortBy () The sortBy method allows using dot notation format to access deeper key in order to sort a multi-dimensional array. 3 SortByDesc ()
And as well as how to use laravel eloquent wherein with arrays. The following syntax represents the whereIn eloquent method in laravel: Column_name:- Your database table column name. Array: – array with comma-separated values. Let’s take look at some example of whereIn () eloquent method in laravel:
Column_name:- Your database table column name. Array: – array with comma-separated values. Let’s take look at some example of whereIn () eloquent method in laravel: In this query, the data will be get from the DB table. Whose ids will be 10, 15, 18.
Column_name:- Your database table column name. Array: – array with comma-separated values. Let’s take look at some example of whereIn () eloquent method in laravel: In this query, the data will be get from the DB table.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With