0

Hi I am trying to write a search function that finds all the service name with the keyword

$serviceids = Service::where('service_name', 'like', '%' . $key . '%')->pluck('service_recordid');

Here is what I have right now but when I search for 'rent' this result also returns 'parent' since rent is included. What can I do to make the condition to be a unique word of its own?

  • Check this answer out, I think you can do what you want with regex - https://stackoverflow.com/a/5743583/1594754 – Bryan Feb 12 '21 at 14:09

1 Answers1

0

Your current search uses % before and after the searchterm. By doing so you actually add the behaviour you don't want - your search for anything that CONTAINS your term.

$serviceids = Service::where('service_name', $key)->pluck('service_recordid');

A simple where without like and % will return any serviceId with the exact key as name

Edit: If you want to ensure a full match to a word you can do it with multiple where clauses (Match only entire words with LIKE?)

$serviceids = Service::where('service_name', 'like', '% ' . $key . ' %')
                       ->orWhere('service_name', 'like', '% ' . $key)
                       ->orWhere('service_name', 'like', $key . ' %')
                       ->orWhere('service_name', $key)
                       ->pluck('service_recordid');

the spaces are key to ensure it has a direct fit

Frnak
  • 6,601
  • 5
  • 34
  • 67