Home » Laravel: Create Multiple Where Clause Query Using Eloquent

Laravel: Create Multiple Where Clause Query Using Eloquent

Laravel Eloquent query
Share this post:

In this post, I will show you how to create multiple where clause queries using Laravel Eloquent. First, we will look at a kind of naive way of having multiple where clauses chained in Eloquent query and after that, we make a more concise query.

Assuming we have a table named chairs and of course, an Eloquent model named Chair, for the table chairs table.

Let’s try to get some chairs that match certain filters that we apply in the query:

Naive Query

$results = Chair::where('category', '=', 'wooden')
    ->where('name', 'LIKE', '%foo%')
    ->where('legs', '=', 3)
    ->where('color', '=', 'brown')
    ->where('height', '>', 2)
    ->where('has_back_rest', '=', 1)
    ->get();

As you can see from the query above we’re basically repeating the method chaining “->where()”. It means that if there are 20 where conditions we end up having ->where() 20 times. That will not look so clean.

How can we shorten the query and remove the repeated where calls? Array of conditions to the rescue!

Improved Query

The solution is actually a simple one. All we need to do is build an array of conditions pass it to one where() method call, like this:

$conditions = [
    ['name', 'LIKE', '%foo%'],
    ['category', '=', 'wooden'],
    ['legs', '=', 3],
    ['color', '=', 'red'],
    ['height', '<', 4],
    ['has_back_rest', '=', 1],
];

$results2 = Chair::where($conditions)->get();

Another useful thing about the improved approach is that if we need to run similar query elsewhere in out code, we can reuse the the same query by making a simple helper function that takes in the request, build the conditions array and return it.

Happy coding!

Leave a Reply

Your email address will not be published.