0

Hi I am using the following function to return results from a users keyword search:

public function search(Request $request)
    {
        $q = $request->query('q');
        $keywords = explode(" ", $request->query('q'));
        $resources = Resource::where(function ($query) use ($keywords) {
                                    foreach ($keywords as $keyword) {
                                        $query->orWhere('title', 'like', "%{$keyword}%");
                                    }
                                })
                                ->orWhere(function ($query) use ($keywords) {
                                    foreach ($keywords as $keyword) {
                                        $query->orWhere('description', 'like', "%{$keyword}%");
                                    }
                                })
                                ->paginate(20);
        return view('resources.search',compact('resources','q'));
    }

This works relatively ok, but it is returning results that contain part of the keyword. i.e if I search for Bot it is returning results that have 'both' in the title or description

Is there anyway I can only return results that match the full word?

Pedro
  • 1,148
  • 4
  • 16
  • 35

1 Answers1

0

Maybe try adding a space before and after the keyword in your query? Something like:

 $query->orWhere('title', 'like', "% {$keyword} %");
danboh
  • 758
  • 2
  • 11
  • 28
  • 1
    Try using a reg exp as indicated here -> https://stackoverflow.com/questions/35306482/laravel-search-for-specific-word – danboh Feb 04 '19 at 21:12