How to Use Where in Eloquent: Simple Query Filtering in Laravel
In Laravel Eloquent, use the
where method to filter query results by specifying a column, an operator, and a value. For example, User::where('age', '>', 18)->get() fetches users older than 18. You can chain multiple where calls for complex filters.Syntax
The where method filters records based on a condition. It accepts three parameters: column (the database field), operator (like =, >, <, etc.), and value (the value to compare). The operator is optional and defaults to '=' if omitted.
php
Model::where('column', 'operator', 'value')->get(); // Operator is optional: Model::where('column', 'value')->get();
Example
This example fetches all users whose status is 'active' and age is greater than 18. It shows how to chain multiple where conditions.
php
<?php use App\Models\User; $users = User::where('status', 'active') ->where('age', '>', 18) ->get(); foreach ($users as $user) { echo $user->name . "\n"; }
Output
Alice
Bob
Charlie
Common Pitfalls
- Forgetting the operator defaults to '='; writing
where('age', 18)meansage = 18. - Using wrong operators like '==' instead of '=' causes errors.
- Not chaining
wherecalls properly can lead to unexpected results.
php
<?php // Wrong: Using '==' operator User::where('age', '==', 18)->get(); // Error // Right: User::where('age', '=', 18)->get(); // Or simpler: User::where('age', 18)->get();
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Basic where | Filter by column equals value | User::where('status', 'active')->get() |
| Where with operator | Filter by column with operator | User::where('age', '>', 18)->get() |
| Multiple where | Chain conditions | User::where('status', 'active')->where('age', '>', 18)->get() |
| Where with default operator | Operator defaults to '=' | User::where('name', 'John')->get() |
Key Takeaways
Use the where method to filter Eloquent queries by column, operator, and value.
The operator parameter is optional and defaults to '=' if omitted.
Chain multiple where calls to combine conditions easily.
Avoid using invalid operators like '==' which cause errors.
Remember where('column', value) means where column equals value.