Home > Enterprise >  Laravel where like on two strings
Laravel where like on two strings

Time:04-27

I would like to improve my search function. Lets say for example the user types in "Letter contract" and in my database i have saved the following string "Letter employment contract". Using the following code will not return anything:

Letter::where('title', 'LIKE', '%' . $search . '%)->get()

Since the search is not looking into "Letter" alone and "Contract" alone in the context. Anyways i can fix this?

Update I tried the following code sample but still didn't get anywhere

$searchValues = preg_split('/\s /', $this->attributes['q'], -1, PREG_SPLIT_NO_EMPTY);

        $model = $model->whereTranslationLike('title', "%{$this->attributes['q']}%");
       
            foreach ($searchValues as $value) {
                $model->orWhereTranslationLike('title', "%{$value}%");
            }

CodePudding user response:

A very naive (but simple) solution would be first to split the search string into individual words, then adding them to the query individually.

$words = explode(' ', $search);

$query = Letter::query();

foreach ($words as $word) {
    $query->where('title', 'LIKE', "%{$word}%");
}

$letters = $query->get();

This implementation doesn't scale very well, but it should get you thinking in the right direction.

CodePudding user response:

There is no issue with your first code but for me, if I wanted to do like you, my code will be like so

$letters = Letter::where("title", "LIKE", "%{$search}%")->get()

I wish this syntax helps you.

  • Related