Home > Back-end >  Laravel/Searchbar : how to search around several words
Laravel/Searchbar : how to search around several words

Time:04-07

I try to make a searchbar where you can request several words : For example, input is "word#1" and "word#2". I would like the returned results to be rendered with either of the entered words. Currently, I have this function in my controller but which prohibits a search on several independent words, I have tried several solutions but they do not work.

public function search()
    {
        $data = [
            'title'=> $description = 'Recherche sur '.config('app.name'),
            'description'=> $description,
            'heading'=> config('app.name'),
        ];
        
        $q = request()->input('q');

        $products = Product::where('title','like',"%$q%")
                    ->orWhere('subtitle','like',"%$q%")
                    ->orWhere('description','like',"%$q%")
                    ->paginate();
        
        return view('products.search', $data)->with('products', $products);
    }

Can you help me please ?

CodePudding user response:

Since you want to search with all the words entered input, in your code you must loop it word per word. e.g.

    $q = request()->input('q');
    $words = explode(' ', $q);

    $query = Product::query();

    foreach ($words as $word) {
        $query->orWhere('title','like',"%$word%")
            ->orWhere('subtitle','like',"%$word%")
            ->orWhere('description','like',"%$word%");
    }

    $products = $query->paginate();
  • Related