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

samalapsy's avatar

How to write Eloquent OrderBy() to put null columns to the last

Please hoe can I write an eloquent query to sort result by a column making all the null columns item appear last. Here is my code

->orderBy('images_id', 'DESC')  // This should show the ones with value first
->distinct()->Paginate(24);
0 likes
4 replies
Cronix's avatar

With normal mysql, you'd add a - sign before the column, like -images_id. Don't know if that will work with query builder/eloquent or not, but it if doesn't you can use orderByRaw() and manually enter your order portion of the query.

3 likes
samalapsy's avatar

This is not still sorting the code..

orderByRaw('-images_id', 'DESC')
WouterClaes's avatar

the syntax of the post from @samalapsy should be

orderByRaw('-images_id DESC')

without the parameters

3 likes

Please or to participate in this conversation.