Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Using whereNull and whereNotNull in Eloquent Collection in Laravel

Working with Laravel Eloquent, we always had this ability to check null fields when builing queries on models. For instance, if you want to check if email_verified_at field is null or not, you’d check it like so.

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

This wasn’t the case if you want to do the same thing on collection. In order to check the similar condition, you’d check manually like so.

$users = User::all();

$unverifiedUsers = $users->whereStrict('is_verified_at', null);

$verifiedUsers = $users->where('is_verified_at', '!==', null);

But things has been changed from Laravel version 6.15.1. There’s this PR #31425 which adds whereNull and whereNotNull to Collection as well. So now, you’d be able to perform the similar condition which you’re used to perform on Query builder, on Collection as well. Here’s how you could do it.

$users = User::all();

$unverifiedUsers = $users->whereNull('is_verified_at');

$verifiedUsers = $users->whereNotNull('is_verified_at');

As you can see, we’ve got a little convenience in here which I think is always welcomed by the community.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a


👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.