How to Check “if not null” with Laravel Eloquent

To check “if not null” with Laravel Eloquent, you can use the whereNotNull() method. The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull() method that allows us to verify if a specific column’s value is not NULL.

For instance, let’s say you have a products table, and you want to retrieve all products where the sku_id is not null:

$products = Product::whereNotNull('sku_id')->get();

If you are only interested in the first result, you can use the first() method instead:

$products = Product::whereNotNull('sku_id')->first();

To retrieve products where multiple fields are not null, you can chain multiple whereNotNull methods.

$products = Product::whereNotNull('sku_id')->whereNotNull('price')->get();

Laravel Eloquent whereNull()

To retrieve products where sku_id is null, you can use the whereNull() method.

$products = Product::whereNull('sku_id')->get();

Always call the get() method at the end to execute the query and retrieve the results.

Using Laravel DB Facade

If you prefer using the DB facade, you can use the whereNotNull() method like this:

$products = DB::table('products')
            ->whereNotNull('sku_id')
            ->get();

And whereNull() method looks like this:

$products = DB::table('products')
            ->whereNull('sku_id')
            ->get();

Summary table

Method Description Example
whereNotNull It checks for non-null values in a column. Product::whereNotNull('sku_id')->get();
whereNull It checks for null values in a column. Product::whereNull('sku_id')->get();
get() It executes the query and retrieves results. Product::all()->get();
first() It executes the query and retrieves the first result. Product::whereNotNull('sku_id')->first();

That’s all!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.