Luke Vincent Luke Vincent - 4 years ago 100
MySQL Question

Passing two arguments to nested where results in "and `` is null" appended to query

if ($input['search']) {
$args = array($query, $input);
$query->where(call_user_func_array(function($query, $input) {
$query->where('', 'LIKE', '%' . $input['search'] . '%')
->orwhere('sku', 'LIKE', '%' . $input['search'] . '%');
}, $args));
return $query;

Above is a section of my query where I intend to create a nested where clause that resembles:

WHERE = 'name' AND
( LIKE "% example %" or p.sku LIKE "% example %")

I've made use of the 'call_user_func_array' to pass in multiple arguments to the closure (only way I could pass the user input to the where clause).

Unfortunately I receive a query exception that looks a little like this:

Unknown column '' in 'where clause'
LIKE %example% or
LIKE %example% and `` is null

and `` is null has been appended to the end. I think this is something to do with the original where clause needing two arguments but I'm struggling to get around it. Any help would be appreciated.

Answer Source

Try something like this:

if ($input['search']) {
    $query->where(function ($query) use ($input) {
        $query->where('', 'LIKE', '%' . $input['search'] . '%')
            ->orWhere('sku', 'LIKE', '%' . $input['search'] . '%');

You can pass variables to a closure via use.

Reference: Anonymous Functions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download