where(function ($q) use ($cols, $search) { $first = true; foreach ($cols as $col) { if (self::hasJoin($col)) { $exp = explode('.', $col); if (sizeof($exp) > 2) { if ($first){ $whereHas = 'whereHas'; }else{ $whereHas = 'orWhereHas'; } $q->$whereHas ($exp[0], function ($q) use ($exp, $search) { return $q->whereHas($exp[1], function ($q2) use ($exp, $search) { // return $q2->where($exp[2], 'LIKE', '%' . $search . '%'); return $q2->whereRaw('lower(`'.$exp[2].'`) like ?', ['%' . strtolower($search) . '%']); }); }); } else { if ($first){ $whereHas1 = 'whereHas'; }else{ $whereHas1 = 'orWhereHas'; } $q->$whereHas1 // $q->{($first) ? 'whereHas' : 'orWhereHas'} ($exp[0], function ($q) use ($exp, $search) { return $q->whereRaw('lower(`'.$exp[1].'`) like ?', ['%' . strtolower($search) . '%']); // return $q->where($exp[1], 'LIKE', '%' . $search . '%'); }); } } else { if ($first){ $where = 'whereRaw'; }else{ $where = 'orWhereRaw'; } // return $q->whereRaw('lower(`'.$col.'`) like ?', ['%' . strtolower($search) . '%']); $q->$where('lower(`'.$col.'`) like ?', ['%' . strtolower($search) . '%']); // $q->{($first) ? 'where' : 'orWhere'}($col, 'LIKE', '%' . $search . '%'); // $q->{($first) ? 'whereRaw ' : 'orWhereRaw '}($col, 'LIKE', '%' . $search . '%'); } if ($first) { $first = false; } } }); } public static function hasJoin($col) { return sizeof(explode('.', $col)) > 1; } }