adamj
adamj

Reputation: 4792

Laravel: Order by specific ID

I've been looking like crazy but I can't seem to find a way of achieving something similar to this with Laravel's Eloquent:

select id,name 
from friends 
order by id=5 desc

Example taken from the following link: mysql SQL: specific item to be first and then to sort the rest of the items

I was hoping a simple Group::orderBy('id', $id, 'DESC')->get() would work, but no such luck.

I've also looked into using DB instead but the orderBy method for that class takes in exactly the same arguments and doesn't have an option for specific IDs. Are there any alternatives?

Thank you very much for all the help!

Upvotes: 5

Views: 7283

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

not sure , but may be you could try using orderByRaw(), like,

$id = 5;
Group::orderByRaw(DB::raw("FIELD(id, $id)"))
       ->get();

Upvotes: 9

Related Questions