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?

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

4 Comments

That, indeed, looks like the only way to currently do it the Laravel way. Thanks a lot.
You're welcome. And thanks for the edit, copy pasted a bit to fast ;)
Just to add incase this happens to someone else, make sure you add % around the value as it won't work otherwise!
One can also use orWhere if they want OR instead of AND in the query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.