Table of contents

Laravel Eloquent whereNotBetween Query Tutorial and Example

In this tutorial, we will tackle one of Laravel's convenient database query builder.
The Laravel eloquent whereNotBetween method. This method returns a query builder instance that selects rows outside the given range of two numbers or dates of a column's value.

 

The Laravel eloquent whereNotBetween method requires two arguments. The first argument is the name of the column. The second argument is an array consisting of two values (starting point and ending point).

 

Syntax:

$query->whereNotBetween('created_at', [$startDate, $endDate]);

 

Example #1: Retrieve User's Followers

For example, you may want to retrieve users' followers, not between 50 and 75.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::whereNotBetween('total_followers', [50, 75])->get();

        dd($users);
    }
}

 

 

Example #2: Retrieve Users Not Between Created Dates

Another example, you may want to retrieve users created not between two dates.

 

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $start = now()->subDays(30);
        $end = now();

        $users = User::whereNotBetween('created_at', [$start, $end])->get();

        dd($users);
    }
}

 

I hope it helps you understand more about Laravel Eloquent whereNotBetween() method.

 

Cheers :)