Remove "having" from query builder using custom helper function
$query = ...->orHaving('col1', 'like', %text%)->orHaving('col2', '=', 123);
$this->removeHaving('col1', $query); //removes it entirely
This code works for all
->having
,
orHaving
,
havingRaw
and
orHavingRaw
public function removeHaving(Builder $builder, $havingColumn)
{
  $bindings = $builder->getQuery()->bindings['having'];
  $havings = $builder->getQuery()->havings;

	if($havings){
		$havingKey = false;
    $isRaw = false;
		foreach ($havings as $key => $having) {

			if (isset($having['column']) && $having['column'] == $havingColumn) {
				$havingKey = $key;
				break;
			}elseif(isset($having['type']) && $having['type'] === "Raw" && stripos($having['sql'], $havingColumn) !== false){
        $isRaw = true;
        $pattern = '/(or|and|(?:(?P<case1namE>)\() ?|) ?\w*(\.)?'.$havingColumn.'( like| ?\=) ?\?(?:(?P=case1namE) OR)?( and)?/mi';

        $havings[$key]['sql'] = preg_replace($pattern, '', $having['sql']);
        unset($bindings[$key]);
      }
		}

		if ($havingKey !== false && !$isRaw) {
			unset($bindings[$havingKey]);
			unset($havings[$havingKey]);
		}

    $havings = empty($havings) ? null : $havings;

		$builder->getQuery()->havings = $havings;
		$builder->getQuery()->bindings['having'] = $bindings;

	}

  return $builder;
}
by გიორგი უზნაძე
4 years ago
Laravel
Eloquent
0
Pro tip: use ```triple backticks around text``` to write in code fences