Skip to content

Instantly share code, notes, and snippets.

@praisedare
Last active January 18, 2024 14:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save praisedare/32df25d0937c877f7a8957afebf232b6 to your computer and use it in GitHub Desktop.
Save praisedare/32df25d0937c877f7a8957afebf232b6 to your computer and use it in GitHub Desktop.
<?php
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) {
$relations = explode('.', $attribute);
$is_top_level_relationship = true;
$deepSearch = function (Builder $query) use (&$relations, &$deepSearch, &$searchTerm, &$is_top_level_relationship) {
if (count($relations) > 1) {
if ($is_top_level_relationship) {
$is_top_level_relationship = false;
$query->orWhereHas(array_shift($relations), $deepSearch);
} else {
$query->whereHas(array_shift($relations), $deepSearch);
}
} else {
$query->where($relations[0], 'LIKE', "%{$searchTerm}%");
$is_top_level_relationship = true;
}
};
$deepSearch($query);
},
function (Builder $query) use ($attribute, $searchTerm) {
$query->orWhere($attribute, 'LIKE', "%{$searchTerm}%");
}
);
}
});
return $this;
});
@archmaster01
Copy link

archmaster01 commented Oct 25, 2023

Thanks so much for this @praisedare, it makes my app search capabilities so much more powerful!! You are a master!

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