Last active
December 5, 2024 13:42
-
-
Save praisedare/32df25d0937c877f7a8957afebf232b6 to your computer and use it in GitHub Desktop.
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
| <?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; | |
| }); |
Author
Thanks so much for this @praisedare, it makes my app search capabilities so much more powerful!! You are a master!
@praisedare - I was wondering, since orWhereHas() supports nested relationships, will it work if we tweak the part where $relationName and $relationAttribute are set in the original article?
Something like this:
$lastDotPosition = strrpos($attribute, '.');
$relationName = substr($attribute, 0, $lastDotPosition);
$relationAttribute = substr($attribute, $lastDotPosition + 1);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An improvement to Freek Van der Herteen's
whereLikequery builder macro. Instead of only being able to search on the first level of relationships, e.guser.name, this allows you to search on arbitrarily nested relationships e.g.post.user.name,comment.post.user.name, e.t.c