TechnicalEloquent performance

Eloquent performanceLesson 19 of 28

Ordering With NULLs Always Last

NULLs last: order by "is null" first. Whitelist any direction you put in raw SQL.

2 min readIntermediateLesson

Eloquent performance19

The problem

Ascending sorts put empty (NULL) values first. You want them at the bottom whichever way you sort.

The fix

Sort by "is it null?" first, then by the real column.

✕ Instead of this

Book::orderBy('town', 'asc');
// empty towns come first

Book::orderByRaw('town '.request('direction').' nulls last');
// SQL injection: user input in raw SQL

✓ Do this

$direction = strtolower(request('direction')) === 'asc' ? 'asc' : 'desc';

Book::orderByRaw('town is null')->orderBy('town', $direction);

The benefit

Empty values always sit at the bottom, in both directions, and the direction can't be abused.

More detail

Postgres has this built in (order by town desc nulls last). You can wrap it in a reusable macro in AppServiceProvider::boot():

use Illuminate\Database\Query\Builder;

Builder::macro('orderByNullsLast', function ($column, $direction = 'asc') {
    $column = $this->getGrammar()->wrap($column);
    $direction = strtolower($direction) === 'asc' ? 'asc' : 'desc';

    return $this->orderByRaw("$column $direction nulls last");
});

Why it works

town is null is 0 for filled rows and 1 for empty ones. Sorting by it ascending always puts filled rows first.

Watch out

  • SQL injection: never put the request's direction straight into orderByRaw. Keywords like asc/desc can't be bound, so whitelist them.
  • wrap() makes sure the column name is treated as a name, not as SQL.

Frame from lesson 19

The orderByNullsLast macro in AppServiceProvider::boot(). It wraps the column with getGrammar()->wrap(), whitelists the direction, then calls orderByRaw("$column $direction nulls last").

Key takeaway

NULLs last: order by "is null" first. Whitelist any direction you put in raw SQL.

Check yourself

Why can't you pass the sort direction as a ? binding?

Reveal answer

✓ Answer

Bindings are for values, not SQL keywords. A bound "desc" would be treated as a string.