How do you check if a field is NOT NULL with Eloquent?


In the Eloquent Model you can make use of whereNotNull() method to get the not null values from the database.

Example 1

In this example we are checking the field rememer_token if it’s NOT NULL.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $users = User::whereNotNull('remember_token')->get(); foreach($users as $user) { echo $user->name."<br/>"; } } }

Output

The output for above is −

Siya Khan
Heena Khan
Seema

The sql query for above is −

SELECT *
FROM users
WHERE remember_token IS NOT NULL;

Output

The output of the above code is −

Example 2

Using DB facade, you can do the same thing as shown below −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class UserController extends Controller{ public function index() { $users = DB::table('users') ->whereNotNull('remember_token') ->get(); foreach($users as $user) { echo $user->name."<br/>"; } } }

Output

The output of the above code is −

Siya Khan
Heena Khan
Seema

Example 3

The method whereNull() helps you to get the field with NULL value. In eloquent model the example is as follows −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $users = User::whereNull('remember_token')->get(); foreach($users as $user) { echo $user->name."<br/>"; } } }

Output

The output of the above code is −

Neha Singh
d7jhMWRMQe
k118AjAswp
7ZH2Vk0TAp
w8QSXDIBVU
feO56tC0sO
MntJcvWT2L
RANLQbtj44
bben5rsdVv

Example 4

In case of DB facade the whereNull() method is used as shown below −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class UserController extends Controller { public function index() { $users = DB::table('users') ->whereNull('remember_token') ->get(); foreach($users as $user) { echo $user->name."<br/>"; } } }

Output

The output for above is −

Neha Singh
d7jhMWRMQe
k118AjAswp
7ZH2Vk0TAp
w8QSXDIBVU
feO56tC0sO
MntJcvWT2L
RANLQbtj44
bben5rsdVv

Updated on: 30-Aug-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements