3

I am trying to sort a query (to a postgresql database) in laravel so that nulls are last.

The code for the order by is

$dbObj->orderBy($aSearchFilters["sidx"],$aSearchFilters["sord"]);

I found How to sort NULL values last using Eloquent in Laravel but all of these have a fixed column that is being sorted on. Is their a way of getting NULLS LAST added to the order by without introducing sql injection issues?

Community
  • 1
  • 1
Catprog
  • 267
  • 3
  • 13
  • Should escaping the input values before passing them to `DB::raw()` solve your concern? See http://stackoverflow.com/questions/23326695/how-to-escape-a-query-using-an-eloquent-model-select – PaePae Nov 17 '15 at 09:41
  • No. Postgres does not like it when you have something like ORDER BY 'colName' – Catprog Nov 18 '15 at 22:40
  • Use `orderByRaw`. Its second parameter is bindings, so it is injection-protected. – shukshin.ivan Sep 20 '16 at 08:42
  • Please Check [this](https://stackoverflow.com/questions/17644072/how-to-sort-null-values-last-using-eloquent-in-laravel) accepted answer. – Usman Dec 14 '21 at 15:17

1 Answers1

5

orderByRaw is an injection-protected method. In the following example I order by a nullable field. The biggest field comes first, NULLs comes after the smallest field.

Posts::where('type', 'fix')
    ->orderByRaw('field DESC NULLS LAST')
shukshin.ivan
  • 11,075
  • 4
  • 53
  • 69