Use the òrderByRaw
query builder method to add a raw "order by" clause to the query.
The method's signature is
$this orderByRaw(string $sql, array $bindings = [])
So it expects a raw sql query as an argument, let's give it one using the DB
facade providing the desired $ids_ordered
as a string
$idArray = [
0 => 1,
1 => 1788,
2 => 887,
3 => 697,
4 => 719,
];
$ids_ordered = implode(',', $idArray); // Basically casts the array values to a string
$customers = Customer::whereIn('id', $idArray)
->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))
->get();
return $customers;
The raw sql query would be like (assuming MySQL
as a DB engine)
select * from `customers` where `id` in (?, ?, ?, ?, ?) order by FIELD(id, 1,1788,887,697,719)
Results:
[
{
"id": 1,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
},
{
"id": 1788,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
},
{
"id": 887,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
},
{
"id": 697,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
},
{
"id": 719,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
}
]