How to Create Multiple Where Clause Query Using Laravel Eloquent

Vineeth Vijayan
Vineeth Vijayan
Published in
2 min readMay 29, 2020

--

Eloquent is a beautiful Active Record implementation provided by Laravel. The framework Laravel itself is written and documented in a beautiful and well readable manner. So as a developer its an obvious feeling to write better looking code in Laravel.

So when usually I just write an eloquent query for lets say listing of products. Then comes the requirements to add different conditions to filter the query. So then many “where” conditions adds up to the query and it becomes like long list of where conditions. And obviously it doesn't look elegant.

So for this we can do multiple methods to refractor the query and make it look more elegant. For example, lets take the case of a Laravel eloquent query with 5 conditions, and this is how it will looks before refractories.

R

There are two methods we can refractor this to more readable code,

Method 1: Passing conditions as array

Method 2: Use query scopes

Use any of these methods if you come across a requirement to write multiple conditions in a single query.

After writing a piece of code just have a look at it, if it doesn't look readable to you, there is always a way to refactor your code. Laravel also provides too many helper functions for us to make our code more readable and make our functions more leaner.

Happy Coding!

Love this article? Click here to buy me a coffee :)

--

--

Vineeth Vijayan
Vineeth Vijayan

Software Engineer | Scribbler | Loves coding and movies | Passive Reader | Lazy Blogger