Last updated on September 9, 2021
In this post, we gonna look at using Laravel’s Eloquent ORM and Query Builder methods to query data from the database where the field is null and where the field is not the null scenario.
Check if null: whereNull
Let’s assume you have a task table and you want to get all the task list where there are no views.
SQL:
SELECT * FROM task WHERE views IS NULL;
Laravel Eloquent
Task::whereNull('views')->get();
Laravel Query Builder
DB::table('task')->whereNull('views')->get()
Check if not null: whereNotNull
Let’s assume you have a task table and you want to get all the task lists where there are views.
SQL:
SELECT * FROM task WHERE views IS NOT NULL;
Laravel Eloquent
Task::whereNotNull('views')->get();
Laravel Query Builder
DB::table('task')->whereNotNull('views')->get()