Ad

LARAVEL 5.8 - Multiple Conditions For WHERE LIKE Clause Using Array In Foreach Not Giving Complete Results

I have a column in my DB table which has multiple comma separated values and I have a comma separated array below:

$possibleSubMods = ["Pre-Op","Perioperative","PREOP","Endoscopy Nurse","Endoscopy","Endoscopy Lab"];

And column have the following values:

column name: subModality
Rows:
Post Anesthesia Care Unit Nurse (PACU), Pre-Op
Pre-Op, Endoscopy Nurse
PREOP, Endoscopy Lab

My code is:

$jobs = DB::table('joblists')
                ->where(function ($query)   use ($possibleSubMods ){
                    foreach ($possibleSubs2 as $subModality) {
                        return $query->where('subModality', 'like', "%" . $subModality . "%");
                    }
                })->count();

It only returns rows having 'Pre-Op' in the subModality colum, remember the 'Pre-Op' is the first value placed in $possibleSubMods array.

Please, suggest me the quick and robust solution, I am using Laravel 5.8! TIA!

Ad

Answer

You may use

$jobs = DB::table('joblists')->where(function ($query) use ($possibleSubMods ){
       foreach ($possibleSubs2 as $key => $subModality) {
            if ($key === 0)
                 $query->where('subModality', 'like', "%" . $subModality . "%");
            else
                 $query->orWhere('subModality', 'like', "%" . $subModality . "%");
       }
})->count();
Ad
source: stackoverflow.com
Ad