Created
November 25, 2021 07:29
-
-
Save ArtMin96/460e9bc530f7a34a91fb8ce815b5d875 to your computer and use it in GitHub Desktop.
whereLike macro with relationship
This file contains 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
/** | |
* 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