Skip to content

Instantly share code, notes, and snippets.

@willvincent
Created June 2, 2025 22:13
Show Gist options
  • Save willvincent/5e7a7cf2b223ed0faaaf3be293c1a576 to your computer and use it in GitHub Desktop.
Save willvincent/5e7a7cf2b223ed0faaaf3be293c1a576 to your computer and use it in GitHub Desktop.
Case insensitive orderBy macro
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
class BuilderMacroServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void {}
/**
* Bootstrap services.
*/
public function boot(): void
{
$macro = function (string $column, string $direction = 'asc') {
$dir = strtolower($direction) === 'desc' ? 'DESC' : 'ASC';
/** @var \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $this */
$grammar = $this->getConnection()->getQueryGrammar();
$wrapped = $grammar->wrap($column);
return $this->orderByRaw("UPPER($wrapped) $dir NULLS LAST");
};
QueryBuilder::macro('orderByUpper', $macro);
EloquentBuilder::macro('orderByUpper', $macro);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment