Laravel 8 whereNotBetween query example

Laravel eloquent method whereNotBetween is contrary of whereBetween method. When you may want to get records for a field value not between two values. For example, you want to get users which doesn't have id between 25 to 50.

In this article, we will see how we can get records in which specific field value is not between two value. whereNotBetween() method works same as whereNotBetween() method. It simply compares field value with two values. Let's first get records by id not between two values.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $users = Users::whereNotBetween('id', [25, 50])
            ->get();

    dd($users);
}

This will return users having ids not between 25 and 50. The above query is same as SQL:

SELECT * FROM `users` WHERE `id` NOT BETWEEN 25 AND 50;

Now let's get users which are not registered between two dates. We can even use standard timestamp value instead of Carbon. Now let's take an example: We want to get users not registered between 2021-10-01 and 2021-10-10.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $start_date = '2021-10-01 00:00:00';
    $end_date = '2021-10-10 23:59:59';

    $users = Users::whereNotBetween('created_at', [$start_date, $end_date])
            ->get();

    dd($users);
}

We can also use whereNotBetween() method with \DB facade instead of Model. For example,

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $users = \DB::table('users')
            ->whereNotBetween('id', [25, 50])
            ->get();

    dd($users);
}

I hope it will help you.