Search code examples
phplaraveleloquentwhere-clausesql-like

Using a single array to pass multiple WHERE conditions (with LIKE)


Theory

It's been discussed that one can use the following code to pass multiple WHERE clauses to single where() method in Laravel's Eloquent:

$condition = array('field_1' => 'value_1', 'field_2' => 'value_2');
$users = User::where($conditon)->get();

The code above simply chains the array's key-value pairs with AND, generating this:

SELECT * FROM `users` WHERE field_1 = value_1 AND field_2 = value_2;

Problem

The key-value pairs above base on equality. Is it possible to use the same implementation for strings, where instead of = we use LIKE?

Abstract example of what I mean:

$condition = array(
                array('field_1', 'like', '%value_1%'),
                array('field_2', 'like', '%value_2%')
             );
$users = User::where($conditon)->get();

This can for sure be done with multiple ->where(...) usage. Is it doable with passing a single array, though?


Solution

  • No not really. But internally Laravel just does it with a loop as well.

    Illuminate\Database\Query\Builder@where

    if (is_array($column))
    {
        return $this->whereNested(function($query) use ($column)
        {
            foreach ($column as $key => $value)
            {
                $query->where($key, '=', $value);
            }
        }, $boolean);
    }
    

    I suggest you do something like this:

    $condition = array(
                    'field_1' => '%value_1%',
                    'field_2' => '%value_2%'
                 );
    
    $users = User::where(function($q) use ($condition){
        foreach($condition as $key => $value){
            $q->where($key, 'LIKE', $value);
        }
    })->get();