Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bobmyles's avatar

Writing a SQL Query into Eloquent

I have a query as below, I am struggling to write it into Eloquent,

SELECT id, description FROM turnovers ORDER BY CASE WHEN id = (SELECT MAX(id) FROM turnovers) THEN 0 ELSE 1 END, id;

The model is Turnover.

Any help is appreciated.

0 likes
1 reply
bobbybouwmann's avatar
Level 88

You can use a raw query to achieve this! However Laravel also has a helper method called orderByRaw which works in your case

DB::table('turnovers')
    ->select('id', 'description')
    ->orderByRaw('CASE WHEN id = (SELECT MAX(id) FROM turnovers) THEN 0 ELSE 1 END, id');

Note: I didn't tested this query, but it should push you in the right direction ;)

Source: https://laraveldaily.com/know-orderbyraw-eloquent/

Please or to participate in this conversation.