Skip to content

Laravel Eloquent whereNull() Query Example

The whereNull() method in Laravel’s Eloquent ORM allows you to filter query results based on whether a specific column’s value is NULL. Here’s an example:

Let’s say you have a users table and you want to fetch all users whose deleted_at column is NULL. This column might be used for soft deletes in Laravel, where instead of removing records from the database, you mark them as deleted.

Assuming you have a User model corresponding to the users table

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
}

You can use whereNull() in your controller or wherever you’re executing the query

use App\Models\User;

// Fetch users where deleted_at is NULL
$users = User::whereNull('deleted_at')->get();

// You can then use $users as needed, for example:
foreach ($users as $user) {
    // Access user properties
    echo $user->name;
}

This code queries the users table using Eloquent and retrieves all records where the deleted_at column is NULL.

Conversely, if you want to fetch records where deleted_at is not NULL, you can use whereNotNull()

// Fetch users where deleted_at is NOT NULL
$users = User::whereNotNull('deleted_at')->get();

Both whereNull() and whereNotNull() are powerful tools in Eloquent for filtering query results based on the presence or absence of NULL values in a specific column. Adjust these queries according to your actual column names and table structure in your application.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments