Created
May 15, 2024 17:01
-
-
Save semihkeskindev/9338b3fd4941bac162cb28bd64264f9c to your computer and use it in GitHub Desktop.
Laravel Eloquent Model Builder Macro - Search
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
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; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Important Note: The macro has package dependency.
Package: https://github.com/mpyw/eloquent-has-by-non-dependent-subquery