order by nulls first in descending order in laravel

1.9k views Asked by At

I want to sort the values of the table in descending order and the null value is in the first, like this:

null
null
2020-09-27 16:36:17 
2020-09-27 18:20:30
2020-09-27 22:45:26
2020-09-28 02:11:14
2020-09-28 10:31:43

I used the following code but it did not work

Source::orderBy('last_rank_update', 'asc')->get();

how can i achieve that?

1

There are 1 answers

0
GMB On BEST ANSWER

In an ascending sort, null values appear last by default (and first in a descending sort). Postgres provide a way to override the default sort ordering null with option nulls first and nulls last.

You could use it with orderByRaw:

Source::orderByRaw('last_rank_update nulls first')