whereNull And whereNotNull Laravel 9 Eloquent Query Tutorial

Laravel 9 whereNull And whereNotNull Eloquent Query Tutorial

 In this post we have explained Laravel 9 whereNull() and whereNotNull() eloquent query tutorial with relevant examples. When our query is served by the database that needs to be data with only null value or NotNull and we can query our database to find out that. Usually we can run queries and check our database for both. We can use Laravel to wrap this up in a small code piece instead. 

Laravel Where Null Eloquent

So we have to get null data values from the database and to do that we will use where null or whereNull() eloquent query in Laravel 9. Let’s say we need to get the users who have not subscribed for two-factor authentication and we are using a field in our user’s table like two_factor_secret to spot them.

<?php
  
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    /**
     * Show a list of resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::whereNull('two_factor_secret')->get();
  
        dd($users);
    }
}

Laravel whereNotNull Eloquent

We have to get not null data values from our database and we will use whereNotNull() or where not null eloquent query to get that data. You can see in the last code piece we queried our database to get users who have not subscribed for two-factor authentication. Let’s see below how whereNotNull eloquent goes: 

<?php
  
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    /**
     * Show a list of resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::whereNotNull('two_factor_secret')->get();
  
        dd($users);
    }
}

So now we know how to use where null and where not null eloquent query needs to be used in Laravel 9. Although it’s just the basic knowledge it still gets the job done and can be used wherever you want.