Search multiple words in same column on laravel

Viewed 503

I need to search multiple words in title column in laravel. Like if i search tea break then i need to fetch only those rows that title content tea and break. If any title contain only tea then it will not come on my result. I have added below code but it's fetch only contain one word row too.

$query->where('title', 'LIKE', "%$search%");

Like if i search Hello Tea break then fetch only those row that contain all three words. that is hello, tea, break.

If i search Hello Tea & break. In this case i will remove the all spacial characters from my code and make below array add on code.

$search = []
$search[0] = 'Hello';
$search[1] = 'Tea';
$search[2] = 'break'
2 Answers

You could instantiate an array containing your search strings, then use the ->orWhere() method on the collection to find them.

$keywords = ['hello', 'tea', 'break'];
$result = $query->where(function ($query) use ($keywords) {
    foreach ($keywords as $keyword) {
       $query->orWhere('title', 'LIKE', "%$keyword%");
    }
});
    $search = ['hello', 'tea', 'break'];
    $pages = Page::query();
    foreach ($search as $word) {
        $pages->orWhere('title', 'LIKE', '%' . $word . '%');
    }
    $pages = $pages->distinct()->get();
Related