devondahon
1 week ago

orWhere with array of search values and wildcard

Posted 1 week ago by devondahon

I have an array of search values set like this:

$string = 'foo bar hello world';
$array = explode(' ', $string);
$array = array_map(fn ($value) => '%' . $value . '%', $array);

Which becomes: ['%foo%', '%bar%', '%hello%', '%world%']

Then, I need to make a search like this:

MyModel::where('col1', 'LIKE', $array[0])
     ->orWhere('col2', 'LIKE', $array[0])

     ->orWhere('col1', 'LIKE', $array[1])
     ->orWhere('col2', 'LIKE', $array[1])

     ->orWhere('col1', 'LIKE', $array[2])
     ->orWhere('col2', 'LIKE', $array[2])

     ->orWhere('col1', 'LIKE', $array[3])
     ->orWhere('col2', 'LIKE', $array[3])

     ->get();

How to make such request programmatically whatever the length of $array is ?

Please sign in or create an account to participate in this conversation.