Laravel Query Builder: Find rows where column is null/not null

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

Introduction

Dealing with databases is an integral part of most web applications and Laravel, as a modern PHP framework, offers a powerful abstraction layer for database interactions: the Query Builder. This tool allows developers to construct queries programmatically, making it easy to perform common tasks such as finding rows where a certain column value is null or not null. In this tutorial, we’ll explore how to harness the Query Builder for these specific conditions.

Understanding NULL in Databases

Before diving into the specifics of the Query Builder, it is important to understand what NULL represents in a database context. A NULL value indicates the absence of any data and is different from an empty string or zero. It can signify that the data is either unknown or not applicable.

Basic Query: Checking for NULL Values

Finding rows with NULL values for a give n column is straightforward in Laravel. Let’s say we have a table named users with a nullable email_verified_at column. To find users who haven’t verified their email address, you can use the whereNull() method:


$unverifiedUsers = DB::table('users')->whereNull('email_verified_at')->get();

This query will return all users where the email_verified_at column is null.

Checking for NOT NULL Values

Conversely, to find rows where a certain column is not null, use the whereNotNull() method. Continuing with the previous example, to get all users who have verified their emails:


$verifiedUsers = DB::table('users')->whereNotNull('email_verified_at')->get();

Combining Conditions

In many cases, you’ll need to combine multiple conditions in a single query. Laravel’s Query Builder equips you with the ability to add as many where() clauses as needed. Supposing we want to find all verified users who are also admins:


$verifiedAdmins = DB::table('users')
    ->whereNotNull('email_verified_at')
    ->where('is_admin', true)
    ->get();

Digging Deeper with Advanced Eloquent ORM

While the Query Builder is powerful, you can often achieve the same result in a more elegant way using Eloquent ORM. Eloquent’s dynamic scope allows for a smoother integration with your models. Here’s how you could find all unverified users utilizing an Eloquent model named User:


$unverifiedUsers = User::whereNull('email_verified_at')->get();

And for verified users:


$verifiedUsers = User::whereNotNull('email_verified_at')->get();

Scopes for Reusability

To maximize the reusability of your queries and keep your code clean, you can define query scopes in your model. For instance, you might add a scope to find all users who have verified their email:


class User extends Authenticatable
{
    public function scopeVerified($query)
    {
        return $query->whereNotNull('email_verified_at');
    }
}

// Use the scope
$verifiedUsers = User::verified()->get();

Nested Conditions and Logical Grouping

Sometimes your logic demands the use of nested conditions and Laravel’s Query Builder handles this gracefully. Let’s imagine you need to retrieve users who are either supervisors or have not yet verified their email, but must have signed up more than a month ago:


$users = DB::table('users')
    ->where(function ($query) {
        $query->whereNull('email_verified_at')
              ->orWhere('is_supervisor', true);
    })
    ->where('created_at', '<', now()->subMonth())
    ->get();

WhereNull and Eloquent Relationships

Another power move in Laravel is leveraging the whereNull and whereNotNull methods within relationship queries. This allows you to filter results based on the presence or absence of related model data. For example, to fetch all blog posts without comments:


$postsWithoutComments = Post::whereDoesntHave('comments')->get();

Utilizing the Query Log for Debugging

When building complex queries, debugging can become difficult. Laravel provides a query log feature for such scenarios. You can enable it, run your queries, and then inspect the log:


DB::enableQueryLog();
// ... run some queries ...
$queryLog = DB::getQueryLog();
print_r($queryLog);

Remember to disable the query log in production as it can lead to performance implications.

Conclusion

Whether you’re filtering for rows with null or not null columns, Laravel’s Query Builder and Eloquent ORM provide elegant and simple solutions. By leveraging these tools, developers can write clear and maintainable code, ensuring their applications handle data precisely and efficiently.