Using where() method in Eloquent to filter query results

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

When dealing with databases in Laravel, the Eloquent ORM is a powerful tool that conveniently allows you to interact with your database using expressive, fluent syntax. One of the most commonly used methods in Eloquent is the where() method, which is instrumental in filtering query results based on certain conditions. In this tutorial, you will learn how to use the where() method effectively to perform various queries ranging from simple to complex in a Laravel application.

Basic Usage of where() Method

The where() method allows you to filter your database query results by a given column. A basic usage of the where() method might look like this:

<?php 
// Fetch users with a status of 'active'. 
$users = App\Models\User::where('status', 'active')->get(); 
?>

This will generate a SQL query similar to: SELECT * FROM users WHERE status = 'active';

Specifying Operators in where()

In addition to checking for equality, you can specify different operators within your where() clause:

<?php 
// Fetch users older than 21 years. 
$users = App\Models\User::where('age', '>', 21)->get(); 
?>

The above code would produce a SQL query comparable to: SELECT * FROM users WHERE age > 21;

Advanced where() Queries

Eloquent also allows you to build more advanced queries using multiple where() clauses, coupled with logical operators:

To find users who are active and either have a role of ‘admin’ or ‘editor’, you can use:

<?php 

$users = App\Models\User::where('status', 'active')
    ->where(function ($query) {
        $query->where('role', 'admin')
              ->orWhere('role', 'editor');
    })
    ->get();

?>

Laravel translates this to the following SQL: SELECT * FROM users WHERE status = 'active' AND (role = 'admin' OR role = 'editor');

where() with Relationships

The where() clause is not just limited to the primary model; you can apply it to relationships as well. Here’s how to use where() to filter results on a related model:

<?php 

// Fetch posts written by active users.
$posts = App\Models\Post::whereHas('author', function ($query) {
    $query->where('status', 'active');
})->get();

?>

The resulting SQL will look like: SELECT * FROM posts WHERE EXISTS ( SELECT * FROM users WHERE posts.author_id = users.id AND status = 'active' );

Dynamic Where Clauses

You can leverage the dynamic nature of Eloquent to build where clauses based on the function naming:

<?php 
// Fetch all users with a name of 'John'. 
$johns = App\Models\User::whereName('John')->get(); 
?>

Will result in: SELECT * FROM users WHERE name = 'John';

Conclusion

Leveraging the where() method in Eloquent helps construct concise and expressive database queries. Whether applying simple conditions or crafting complex filters, Eloquent’s where() provides the needed flexibility in orchestrating the dynamic retrieval of data within a Laravel application.