You can register a macro in your AppServiceProvider.php and use with the query builder for any table across your whole project. In the boot method of your AppServiceProvider.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) { [$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; });
Usage:
$users = User::query(); $users = $users->whereLike(['username', 'name', 'email'], $searchText);
Credits: Freek.Dev
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You can register a macro in your AppServiceProvider.php and use with the query builder for any table across your whole project.
In the boot method of your AppServiceProvider.php:
Usage:
Credits:
Freek.Dev