0

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 ?

Chocogab
  • 5
  • 1
  • So in your example, the value of `$q` is `word#1 word#2`? Can you clarify what kind of output do you want to achieve? What if I input "dog cat" – aceraven777 Apr 07 '22 at 08:32
  • If I input `"dog cat"`, you want all results with either `"dog"` or `"cat"` in it? – aceraven777 Apr 07 '22 at 08:34

1 Answers1

1

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();
aceraven777
  • 4,358
  • 3
  • 31
  • 55
  • Thank you for your answer, which was very appropriate. However, I would still like to improve my research but I can't do it. Can I ask you to please go to this topic? https://stackoverflow.com/questions/72716460/laravel-searchbar-how-to-be-more-relevant-in-a-multi-keywords-search You would help me a lot. – Chocogab Jun 23 '22 at 12:52