Skip to content

Commit

Permalink
fix natural sort + tweak
Browse files Browse the repository at this point in the history
  • Loading branch information
lgtaxn committed Dec 24, 2019
1 parent b3ca263 commit e8e1070
Showing 1 changed file with 26 additions and 23 deletions.
49 changes: 26 additions & 23 deletions src/macros.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,35 +20,38 @@ function($column, $direction = 'asc') {
$column = $this->grammar->wrap($column);
$direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';


return $this->orderByRaw(
"$column + 0 <> 0 ".($direction == 'asc' ? 'desc' : 'asc').", "
. "$column + 0 $direction, "
. "length($column) $direction, "
. "$column $direction"
);
}
);

// Add an Eloquent "whereLike" query builder macro
EloquentBuilder::macro('whereLike', function ($attributes, $searchTerm) {
$searchTerm = str_replace(' ', '%', $searchTerm);

$this->where(function (EloquentBuilder $query) use ($attributes, $searchTerm) {
foreach (Arr::wrap($attributes) as $attribute) {
$query->when(Str::contains($attribute, '.'),
function (EloquentBuilder $query) use ($attribute, $searchTerm) {
list($relationName, $relationAttribute) = explode('.', $attribute);

$query->orWhereHas($relationName, function (EloquentBuilder $query) use ($relationAttribute, $searchTerm) {
$query->where($relationAttribute, 'LIKE', "%{$searchTerm}%");
});
},
function (EloquentBuilder $query) use ($attribute, $searchTerm) {
$query->orWhere($attribute, 'LIKE', "%{$searchTerm}%");
}
);
}
});

return $this;
});
EloquentBuilder::macro(
'whereLike',
function ($attributes, $searchTerm) {
$searchTerm = str_replace(' ', '%', $searchTerm);

$this->where(function (EloquentBuilder $query) use ($attributes, $searchTerm) {
foreach (Arr::wrap($attributes) as $attribute) {
$query->when(Str::contains($attribute, '.'),
function (EloquentBuilder $query) use ($attribute, $searchTerm) {
list($relationName, $relationAttribute) = explode('.', $attribute);

$query->orWhereHas($relationName, function (EloquentBuilder $query) use ($relationAttribute, $searchTerm) {
$query->where($relationAttribute, 'like', "%{$searchTerm}%");
});
},
function (EloquentBuilder $query) use ($attribute, $searchTerm) {
$query->orWhere($attribute, 'like', "%{$searchTerm}%");
}
);
}
});

return $this;
}
);

0 comments on commit e8e1070

Please sign in to comment.