Laravel Query Eloquent whereBetween Example

Sovary August 3, 2022 580
1 minute read

This article we will explain how to use whereBetween query in Laravel 9. we will give a few example to demonstrated how whereBetween query data from database. If you familiar with raw SQL, it will be more easy to understand. 

We are going to use below table named User as sample records to manipulate testing and see how it works. So first please see below table with some record

SQL Equivalent

Before go to whereBetween Laravel eloquent let's see below SQL query which is retrieved data the same result.

select * from `User` where `role` between ? and ?

whereBetween()

whereBetween() -  is used to compare two or more columns value in specific range.

Example #1

$from = date('2014-01-01');
$to = date('2017-12-31');

$users = DB::table('User')
           ->whereBetween('role', [$from , $to])
           ->get();

Output #1

^ Illuminate\Support\Collection {#278 ▼
  #items: array:2 [▼
    0 => {#276 ▶}
    1 => {#281 ▶}
  ]
  #escapeWhenCastingToString: false
}

whereBetween() in Controller File

Now let's Laravel query between two date value to retrieved database.

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function index(Request $request)
    {
      $users= User::whereBetween('created_at',[$request->start_date,$request->end_date])->get();
  
      dd($users);
    }
}

You might also like...

 

Laravel  PHP  Query Builder 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him