Created
June 2, 2025 22:13
-
-
Save willvincent/5e7a7cf2b223ed0faaaf3be293c1a576 to your computer and use it in GitHub Desktop.
Case insensitive orderBy macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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