Laravel Query Eloquent whereBetween Example

Sovary August 3, 2022 599
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him