Searching models using a where like query in Laravel
1 min readJun 1, 2024
From this post you will learn something like this $query->whereLike([‘campaign.title’, ‘campaign.organization.org_name’], $search);
Using a macro
if you want to add a search any model, you can add a macro to the Eloquent's Query builder. If you've never heard of a macro in Laravel read this excellent blogpost on the Tighten Co blog.
Here’s how our macro could look like. You can put it the boot
method of App\Providers\AppServiceProvider
or a service provider of your own.
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->orWhere($attribute, 'LIKE', "%{$searchTerm}%");
}
);
}
});
return $this;
});
With that macro can do something like this:
$query->whereLike(['campaign.title', 'campaign.organization.org_name'], $search);
Hope you found this helpful!