Laravel where Null and where Not Null example. In this tutorial, you will learn how to use whereNull() and whereNotNull() eloquent methods to implementing a query in laravel apps.
As well as you will learn about whereNull and whereNotNull core SQL queries.
The following syntax represents the whereNull and whereNotNull eloquent methods:
whereNull
whereNull('columnName');
whereNotNull
whereNotNull('columnName');
It’s good always practice check null fields when building queries on models.
Example 1: Laravel whereNull Query
Using the following query, you can fetch data from database table users where the name field empty in DB table:
public function index()
{
$users = User::whereNull('name')->get();
dd($users);
}
When you dump the above given whereNull query you will get the following SQL query:
SELECT * FROM users WHERE name IS NULL;
Example 2: Laravel whereNotNull Query
Using the following query, you can fetch data from database table users where the email_verified_at field is not empty in DB table:
public function index()
{
$users = User::whereNotNull('email_verified_at')->get();
dd($users);
}
When you dump the above given whereNotNull query you will get the following SQL query:
SELECT * FROM users WHERE email_verified_at IS NOT NULL;
Conclusion
In this tutorial, you have learned how to use laravel where null and where not null eloquent method with query builder and model.