Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i search multiple keywords in laravel .?

This is my controller

 $term = $request->get('q');

 // return $request->q;

 $products = Post::whereHas('user', function($query) use($term) {
     $query->where('name', 'like', '%'.$term.'%');
 })->orWhere('tags','LIKE','%'.$term.'%')->get();
 return view('pages.search', compact('products','users'));

This is working good for single keyword search. But I want to use it for multiple keywords. Like laravel php etc. Please guide me when I search multiple values like abc php laravel or anything then it should work. If tags exists in different column like php is present in 1st column and laravel is in next column when I search php laravel then it should show me both column values.

like image 375
Muhammad Haroon Avatar asked Nov 02 '25 01:11

Muhammad Haroon


1 Answers

There is probably a better way to do this, like using CloudSearch/Algolia, but this is a solution that has worked for us:

// Split the terms by word.
$terms = explode(" ", request('q'));

$products = Post::query()
    ->whereHas('user', function ($query) use ($terms) {
        foreach ($terms as $term) {
            // Loop over the terms and do a search for each.
            $query->where('name', 'like', '%' . $term . '%');
        }
    })
    ->orWhere(function ($query) use ($terms) {
        foreach ($terms as $term) {
            $query->where('tags', 'like', '%' . $term . '%');
        }
    })
    ->get();
like image 54
Jono20201 Avatar answered Nov 04 '25 18:11

Jono20201



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!