Laravel Eloquent With WhereNull() Query Example

Hello Artisan

in this tutorial i will discuss about laravel whereNull() query example. I will show how to use whereNull() and whereNotNull() in Laravel eloquent query.

You can easily use this whereNull() and whereNotNull() in your eloquent query.  So let's see the example query of whereNull and whereNotNull.

whereNull() will help you to have data with null values from database. The whereNull method filters items where the given key is null

Example: whereNull()

$collection = collect([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);

$filtered = $collection->whereNull('name');

$filtered->all();

//ouput 

/*
    [
        ['name' => null],
    ]
*/

 

You can use it with eloquent like

    public function index()
    {
        \App\User::select("*")
                 ->whereNull('email_verified_at')
                 ->get()->dd();
  
        
    }

 

whereNotNull() will help you to have  data with not null values from database.The whereNotNull method filters items where the given key is not null.

Example: whereNotNull()

$collection = collect([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);

$filtered = $collection->whereNotNull('name');

$filtered->all();

Output

/*
    [
        ['name' => 'Desk'],
        ['name' => 'Bookcase'],
    ]
*/
 

You can use it with eloquent like
 

public function index()
 {
    \App\User::select("*")
            ->whereNotNull('email_verified_at')
            ->get()->dd();
 }

 

Hope it can help you.

 

#laravel #laravel-eloquent