2
votes

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?

1
Should escaping the input values before passing them to DB::raw() solve your concern? See stackoverflow.com/questions/23326695/…PaePae
No. Postgres does not like it when you have something like ORDER BY 'colName'Catprog
Use orderByRaw. Its second parameter is bindings, so it is injection-protected.shukshin.ivan
Please Check this accepted answer.Usman Ali Aslam

1 Answers

4
votes

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')