I'm using the Laravel Eloquent query builder and I have a query where I want a WHERE
clause on multiple conditions. It works, but it's not elegant.
Example:
$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)
->get();
Is there a better way to do this, or should I stick with this method?
In Laravel 5.3 you can use more granular wheres passed as array:
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
useand
operator, you can group them this way:Then:
The above will result in such query:
You can use eloquent in Laravel 5.3
All results
Partial results
As per my suggestion if you are doing filter or searching
then you should go with :
The
whereColumn
method can be passed an array of multiple conditions. These conditions will be joined using theand
operator.Example:
For more information check this section of the documentation https://laravel.com/docs/5.4/queries#where-clauses