Search code examples
phplaraveleloquentcontains

How to implement search with contains using Eloquent


I create a search query with Eloquent like this:

User::where('firstName', 'like', '%' . $search_value . '%')
      ->orWhere('lastName', 'like', '%' . $search_value . '%')
      ->get();

It's work. But I need to search with contains. For examle, if my search value is hello world, I should find row with value World! Okay, hello.

How can I do it?


Solution

  • So the easiest way to achieve this is to use Eloquent Macros:

    use Illuminate\Database\Eloquent\Builder;
    
    // ...
    
    Builder::macro('whereLike', function(string $attribute, string $searchTerm) {
       return $this->orWhere($attribute, 'LIKE', "%{$searchTerm}%");
    });
    

    Now you can search Model like:

    User::query()
       ->whereLike('name', $searchTerm)
       ->whereLike('email', $searchTerm)
       ->get();
    

    More on the subject on: https://freek.dev/1182-searching-models-using-a-where-like-query-in-laravel and https://tighten.co/blog/the-magic-of-laravel-macros