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

Viewed 1597

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;
    }
0 Answers
Related