Skip to content

Instantly share code, notes, and snippets.

@felipepodesta
Forked from reinink/order_by_nulls.php
Created July 17, 2019 16:13
Show Gist options
  • Select an option

  • Save felipepodesta/503be4cddde3ebddfb05ef5df0ce37db to your computer and use it in GitHub Desktop.

Select an option

Save felipepodesta/503be4cddde3ebddfb05ef5df0ce37db to your computer and use it in GitHub Desktop.
<?php
use Illuminate\Database\Query\Builder;
Builder::macro('orderByNulls', function ($column, $direction = 'asc', $nulls = 'last', $bindings = []) {
$column = $this->getGrammar()->wrap($column);
$direction = strtolower($direction) === 'asc' ? 'asc' : 'desc';
$nulls = strtolower($nulls) === 'first' ? 'NULLS FIRST' : 'NULLS LAST';
return $this->orderByRaw("$column $direction $nulls", $bindings);
});
Builder::macro('orderByNullsLast', function ($column, $direction = 'asc', $bindings = []) {
return $this->orderByNulls($column, $direction, 'last', $bindings);
});
Builder::macro('orderByNullsFirst', function ($column, $direction = 'asc', $bindings = []) {
return $this->orderByNulls($column, $direction, 'first', $bindings);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment