Skip to content

Instantly share code, notes, and snippets.

@semihkeskindev
Created May 15, 2024 17:01
Show Gist options
  • Save semihkeskindev/9338b3fd4941bac162cb28bd64264f9c to your computer and use it in GitHub Desktop.
Save semihkeskindev/9338b3fd4941bac162cb28bd64264f9c to your computer and use it in GitHub Desktop.
Laravel Eloquent Model Builder Macro - Search
Builder::macro('search', function ($attributes, $searchTerm, $compact = false): Builder {
$this->where(function (Builder $query) use ($compact, $attributes, $searchTerm): void {
if ($compact) {
$joinedAttributes = '`'.implode('`, " " ,`', $attributes).'`';
$query->orWhereRaw('upper('.\DB::raw("concat({$joinedAttributes})").') LIKE ?', ["%{$searchTerm}%"]);
} else {
foreach ($attributes as $attribute) {
$query->when(
str_contains($attribute, '.'),
function (Builder $query) use ($attribute, $searchTerm): void {
[$relationName, $relationAttribute] = explode('.', $attribute);
$query->orHasByNonDependentSubquery($relationName, function (Builder $query) use ($relationAttribute, $searchTerm): void {
$query->whereRaw('upper('.$relationAttribute.') LIKE ?', ["%{$searchTerm}%"]);
});
},
function (Builder $query) use ($attribute, $searchTerm): void {
$query->orWhereRaw('upper('.$attribute.') LIKE ?', ["%{$searchTerm}%"]);
}
);
}
}
});
return $this;
});
@semihkeskindev
Copy link
Author

Important Note: The macro has package dependency.

Package: https://github.com/mpyw/eloquent-has-by-non-dependent-subquery

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment