Sunday, November 17, 2019

Laravel : How to Create Multiple Where Clause Query Using Laravel Eloquent?


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:
$query->where([
    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])
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', ...];
Then:
$results = User::where($matchThese)->get();

// with another group
$results = User::where($matchThese)
    ->orWhere($orThose)
    ->get();
The above will result in such query:
SELECT * FROM users
  WHERE (field = value AND another_field = another_value AND ...)
  OR (yet_another_field = yet_another_value AND ...)
  • 8
    How do you specify the operator? – Styphon Jan 21 '15 at 14:08
  • 9
    @Styphon You don't. Currently it work only with =. – Jarek Tkaczyk Jan 21 '15 at 15:51
  • 4
    @Styphon and what if i want to make: WHERE (a IS NOT NULL AND b=1) OR (a IS NULL AND b=2); ? – alexglue Jul 30 '15 at 16:47 
  • 8
    You can also pass an array of conditions like this: $users = DB::table('users')->where([ ['status', '=', '1'], ['subscribed', '<>', '1'], ])->get(); – zeros-and-ones Sep 15 '16 at 19:19 
  • 3
    @jarek : How do I include the whereNotIn according to your answer with having other where cluases? –

Link : https://stackoverflow.com/questions/19325312/how-to-create-multiple-where-clause-query-using-laravel-eloquent

No comments:

Post a Comment