How do you check if a field is NOT NULL with Eloquent?

In Laravel's Eloquent ORM, you can check if a field is NOT NULL using the whereNotNull() method. This method filters records where the specified column contains non-null values.

Syntax

The basic syntax for checking NOT NULL fields ?

Model::whereNotNull('column_name')->get();

Using Eloquent Model

Here's how to check if the remember_token field is NOT NULL using an Eloquent model ?

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::whereNotNull('remember_token')->get();
        foreach($users as $user) {
            echo $user->name."<br/>";
        }
    }
}
?>

The output of the above code is

Siya Khan
Heena Khan
Seema

The generated SQL query is

SELECT *
FROM users
WHERE remember_token IS NOT NULL;

Using DB Facade

You can achieve the same result using Laravel's DB facade ?

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    public function index()
    {
        $users = DB::table('users')
            ->whereNotNull('remember_token')
            ->get();
        foreach($users as $user) {
            echo $user->name."<br/>";
        }
    }
}
?>

The output of the above code is

Siya Khan
Heena Khan
Seema

Checking for NULL Values

To check for NULL values instead, use the whereNull() method ?

<?php
$users = User::whereNull('remember_token')->get();
foreach($users as $user) {
    echo $user->name."<br/>";
}
?>

The output shows users with NULL remember_token values

John Doe
Jane Smith
Mike Wilson

Comparison

Method Purpose SQL Equivalent
whereNotNull() Get records with non-null values IS NOT NULL
whereNull() Get records with null values IS NULL

Conclusion

Use whereNotNull() to filter records with non-null values and whereNull() for null values. Both methods work with Eloquent models and DB facade, generating appropriate SQL IS NOT NULL and IS NULL conditions.

Updated on: 2026-03-15T10:10:52+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements