Skip to content

Instantly share code, notes, and snippets.

@ArtMin96
Created November 25, 2021 07:29
Show Gist options
  • Save ArtMin96/460e9bc530f7a34a91fb8ce815b5d875 to your computer and use it in GitHub Desktop.
Save ArtMin96/460e9bc530f7a34a91fb8ce815b5d875 to your computer and use it in GitHub Desktop.
whereLike macro with relationship
/**
* Searching Eloquent models with Relations
*
* Example Post::whereLike(['name', 'text', 'author.name', 'tags.name'], $searchTerm)->get();
*/
Builder::macro('whereLike', function ($attributes, string $searchTerm) {
$this->where(function (Builder $query) use ($attributes, $searchTerm) {
foreach (\Arr::wrap($attributes) as $attribute) {
$query->when(
str_contains($attribute, '.'),
function (Builder $query) use ($attribute, $searchTerm) {
[$relationName, $relationAttribute] = explode('.', $attribute);
$query->orWhereHas($relationName, function (Builder $query) use ($relationAttribute, $searchTerm) {
$query->where($relationAttribute, 'LIKE', "%{$searchTerm}%");
});
},
function (Builder $query) use ($attribute, $searchTerm) {
$query->where($attribute, 'LIKE', "%{$searchTerm}%");
}
);
}
});
return $this;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment