Table of contents
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);
}
}
Â
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);
}
}
Â
Now you have a basic knowledge already about Laravel where null and where not null eloquent query.
Â
That's pretty much it. I hope it helps. Thank you for reading :)
Read next