php - Laravel: How to remove a specific 'where' clause from the Query Builder

I am fairly new to laravel and need to remove a 'where clause' from the Query Builder based on search options being selected or not.
My model contains the following already in a local scope:
$builder->where('users.active', '=', 'Yes');
and I need to override this in a specific search circumstance to either allow values of 'Yes' and 'No', or just remove the clause entirely. This must be done in a Trait and be suitable for multi uses/models.
I have actually got this to work by adding a new method in my SearchTrait that strips the query builder apart, removes the offending column and associated binding and returns the modified query builder.
$builder = static::removeWhere($builder, 'users.active');
This seems to work - but my question(s) are:
- Is this a suitable solution, or is there something more elegant?
- Are there any glaring issues with my solution?
- Is there a better place for this / can I easily extend the 'builder'?
/**
* @param Builder $builder
* @param $whereColumn
* @return Builder
*/
public static function removeWhere(Builder $builder, $whereColumn)
{
$bindings = $builder->getQuery()->bindings['where'];
$wheres = $builder->getQuery()->wheres;
$whereKey = false;
foreach ($wheres as $key => $where) {
if ($where['column'] == $whereColumn) {
$whereKey = $key;
break;
}
}
if ($whereKey !== false) {
unset($bindings[$whereKey]);
unset($wheres[$whereKey]);
}
$builder->getQuery()->wheres = $wheres;
$builder->getQuery()->bindings['where'] = $bindings;
return $builder;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function update() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.