1
votes

I've this code

    $arrayFilter = ['category' => $category,
                    'compartment' => $compartment,
                    'doors' => $doors,
                    'brand' => $brand, 
                    'model' => $model,
                    'area'  => $area,
                    'status'=> $status,
                    'fuel'  => $fuel,
                    'speeds'=> $speeds,
                    'year'  => $year];       
    $queryString = "";
    foreach($arrayFilter as $filter => $val){
        if (!empty($val)){
            $queryString.= "['$filter', '=', '$val'], ";
        }
    }
    echo $qString = mb_substr($queryString, 0, -2, 'UTF-8');
    DB::table('Catalog')->where([$qString])->get();

and receive this error

QueryException in Connection.php line 761:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from Catalog where (0 = ))

What is the problem? In the encoding or in the brackets. $queryString is empty, but it shows the same error when it's full. I can't understand the problem.

2
you seem to be trying to construct a string that looks like how you would define an array in PHP ... are you planning on evaling that string to execute that PHP?lagbox

2 Answers

1
votes

Argument to where() is array. You create a string. Why?

Simply:

$where = [];
foreach($arrayFilter as $filter => $val){
    if (!empty($val)){
        $where[] = [$filter, '=', $val];
    }
}
DB::table('Catalog')->where($where)->get();
0
votes

Just pass that array $arrayFilter directly to where. It can accepts an array as field => value already.

DB::table('Catalog')->where($arrayFilter)->get();

Your array is correct already .. the comparison operator is optional with querying and defaults to '=', when not present.

    ['field' => 'value']

Will end up being:

... WHERE (`field` = ?)