• iconJakarta, Indonesia
  • iconlaratech.channel@gmail.com

+62081290348080

icon

Need Help?

+62081290348080

Laravel Eloquent whereBetween() Method | How to use whereBetween() Query in Laravel

Laravel Eloquent whereBetween() Method | How to use whereBetween() Query in Laravel

Laravel Eloquent whereBetween() Method | How to use whereBetween() Query in Laravel

Hello Everyone, In this article, I will show you how to use Laravel whereBetween() Query. by using the eloquent model.

 

So let's see how we can able to achieve this by following the below examples. step by step.

 

Example 1:

 

Assuming you are trying to get Users' points between ( 100 to 1000 ) to do that we will be using the whereBetween() method as below exaple.

 

<?php
  
    namespace App\Http\Controllers;
  
    use Illuminate\Http\Request;
    use App\Models\User;
  
    class UserController extends Controller
  {
    public function getUserPoints()
  {
        $usersPoints = User::select("*")
        ->whereBetween('userPoints', [100, 1000])
        ->get();

        dd($usersPoints);
    }
}

 

Example 2:

 

Assuming you are trying to get reservation dates between ( 2001 to 2022 ) we can do something like below example.

 

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Reservation;

  
    class ReservationController extends Controller
  {

      public function getOneYearReservation()
    {
        $from = date('2021-01-01');
        $to = date('2022-01-01');
        
        $oneYearReservation =  Reservation::query()
        ->whereBetween('reservation_from', [$from, $to])
        ->get();


        dd($oneYearReservation);
    }
}

 

In some cases you need to add date range dynamically based on the Example 3 below:

 

Reservation::all()->filter(function($item) {

    if (Carbon::now()->between($item->from, $item->to)) {
      return $item;
    }

  });

Thank you for reading this article, if you have anything that you wanted to ask leave your comment and we discuss it. I hope you understand a Laravel Eloquent whereBetween() Method | How to use whereBetween() Query in Laravel by now.
{"id":1,"name":"Laratech","username":"admin","avatar":"users\\June2022\\WSYjSsq966HbiJIgJyhx.png"}

About the author:

Laratech is a fullstack developer based in Indonesia.
You can find more about him at Twitter

0 Comments

Leave a comment

Tags