9

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?

Community
  • 1
  • 1
lesssugar
  • 15,486
  • 18
  • 65
  • 115

1 Answers1

16

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();
Adam Ramadhan
  • 22,712
  • 28
  • 84
  • 124
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270