veksen veksen - 1 year ago 170
PHP Question

How to create multiple where clause query using Laravel Eloquent?

I'm using the Laravel Eloquent query builder and I have query where I want a

clause on multiple things. It works, but it is not elegant.


$results = User::
where('this', '=', 1)
->where('that', '=', 1)
->where('this_too', '=', 1)
->where('that_too', '=', 1)
->where('this_as_well', '=', 1)
->where('that_as_well', '=', 1)
->where('this_one_too', '=', 1)
->where('that_one_too', '=', 1)
->where('this_one_as_well', '=', 1)
->where('that_one_as_well', '=', 1)

Is there a better way to do this, or should I stick with this method?

Answer Source

In Laravel 5.3 you can use more granular wheres passed as array:

    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],

Personally I haven't found use-case for this over just multiple where calls, but fact is you can use it.

Since June 2014 you can pass an array to where

As long as you want all the wheres use and operator, you can group them this way:

$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];

// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];


$results = User::where($matchThese)->get();

// with another group
$results = User::where($matchThese)

The above will result in such query:

  WHERE (field = value AND another_field = another_value AND ...)
  OR (yet_another_field = yet_another_value AND ...)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download