Laravel 7|8 Eloquent whereBetween() Between Database Query Example

Last updated on by Digamber

The whereBetween method in laravel verifies that a column’s value is between two values. This tutorial walks you through an easy example of laravel eloquent wherebetween query.

How to use whereBetween in laravel application? Well, thats what we are going to answer in this tutorial.

This example will show you how to perform wherebetween queries with laravel eloquent wherebetween dates. We will fetch data by executing a query for two values in the database.

Without further ado let’s check out whereBetween() eloquent query in Laravel 7.

<?php
   
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Student;
  
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    
    public function index()
    {
        $students = Student::select("*")
                        ->whereBetween('points', [1, 150])
                        ->get();
  
        print_r($students);
    }
}

Laravel whereBetween method are handy when you require to get records in between two provided dates for the given timestamp column.

<?php
   
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Student;
  
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    
    public function index()
    {
        $startDate = Carbon::now()->subDays(30);
        $endDate = Carbon::now();
  
        $students = User::select("*")
                        ->whereBetween('created_at', [$startDate, $endDate])
                        ->get();
  
        print_r($students);
    }
}

By using carbon its more comfortable to work with dates in Laravel,
Carbon offers unbound easiness. We have completed this tutorial, i hope you liked it.