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?
OR
OR
Query scopes may help you to let your code more readable.
http://laravel.com/docs/eloquent#query-scopes
Updating this answer with some example:
In your model, create scopes methods like this:
Then, you can call this scopes while building your query:
Multiple where clauses
finally getting the result
Conditions using Array:
Will produce query like bellow:
Conditions using Antonymous Function:
Will produce query like bellow:
Be sure to apply any other filters to sub queries, otherwise the or might gather all records.