Laravel 8 Eloquent whereNull() and whereNotNull() Query Example

codeanddeploy

Code And Deploy

Posted on March 28, 2022

Laravel 8 Eloquent whereNull() and whereNotNull() Query Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-wherenull-and-wherenotnull-query-example

In this post, I'm sharing a Laravel 8 eloquent where null and where not null query with a simple example. Usually, when querying your database you need to get data with null values. Or sometimes we need to get or check if the data value is not null. So Laravel already provided a shortcut for this to shorten our code.

Laravel Where Null Eloquent

Using Laravel where null or whereNull() eloquent query. This will help us to get null data values from your database. In my example let's get the users not using two-factor authentication. So let say I have a two_factor_secret field in my user's table.

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::whereNull('two_factor_secret')->get();

        dd($users);
    }
}
Enter fullscreen mode Exit fullscreen mode

Laravel Where Not Null Eloquent

Laravel where not null or whereNotNull() eloquent query will help us to get not null data values from your database. So in my previous code, we get the users without two-factor authentication. Now let's get the users with two-factor authentication.

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::whereNotNull('two_factor_secret')->get();

        dd($users);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now you have a basic knowledge already about Laravel where null and where not null eloquent query.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-wherenull-and-wherenotnull-query-example if you want to download this code.

Happy coding :)

💖 💪 🙅 🚩
codeanddeploy
Code And Deploy

Posted on March 28, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related