Today we are here with a simple tutorial for using multiple where conditions in Laravel. In Laravel there are 2 ways we can use Laravel where clause to effectively fetch data from tables. Here we will only discuss simple use cases and we will omit the complex queries involving multiple conditions packed with other clauses. Laravel multiple where conditions can be used with eloquent as well as with database query builder.
Laravel where condition is the best way to AND queries in Laravel, which is an important part of writing queries. There are many advantages of using query builder to write where conditions. It uses PDO parameter binding to protect applications against SQL injection attacks. There are not many security practices needed from our side when writing where conditions or multiple conditions.
Writing Multiple Where Conditions
This is the first way of writing multiple where conditions where conditions will be added as new methods to the eloquent class or DB query.
$users = DB::table('users')->where('gender', 'female')->where('age', '>', 25)->get();
or
$users = Users::where('gender', 'female')->where('age', '>', 25)->get();
Above query will fetch results from users table with the gender = "female" and age > "25". This is just a basic example and can be done with multiple conditions.
Array in Where Condition
To achieve the same result we can also pass an array to the where condition. Instead of passing parameters to where conditions we can construct an array and pass it to the where condition.
$users = DB::table('users')->where([
['gender', '=', 'female'],
['age', '>', '25'],
])->get();
In the above example, it is just passing an array to the where condition to achieve the same result. And we can also pass multiple where conditions to implement more complex queries. Building queries using arrays has some advantages where we need to pass multiple conditions and construct complex conditions.