Laravel 10 Using whereBetween Query in Laravel

Hello Artisan, today I'll show you How to Using whereBetween Query in Laravel. I'm going to explore Laravel Eloquent's whereBetween() method, which checks if a value in a column falls within a specified range. I'll be sharing some straightforward examples. The following example demonstrates how to use Laravel's Eloquent method for performing whereBetween queries in a straightforward manner.

Table of Contents

  1. Example 1
  2. Example 2

Example 1

In the initial instance, we'll employ the whereBetween() function to narrow down our entries within a specific date range.

In the following illustration, we possess an OrderController responsible for executing the recentOrders function. This function will provide us with orders that have been made during the past week.

<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    /**
     * Display last week orders.
     *
     * @return \Illuminate\Http\Response
     */
    public function recentOrders()
    {
        $from = Carbon::now()->subDays(7);
        $to = Carbon::now();

        $orders = Order::whereBetween('created_at', [$from, $to])
            ->get();

        dd($orders);
    }
}

In the provided code snippet, we used the whereBetween() method in Laravel to filter records based on the two dates, $from and $to.

Example 2

In the following example, we'll use numbers/decimals to narrow down our records. For this illustration, I've got a ProductController that will use a method called filterProducts. This method's job is to give back the products within a price range specified by a minimum and maximum price.

<?php
  
    namespace App\Http\Controllers;
    
    use App\Models\Product;
    use Illuminate\Http\Request;
        
    class ProductController extends Controller
    {
        /**
        * Filter products.
        * @param $min
        * @param $max
        * @return \Illuminate\Http\Response
        */
        public function filterProducts($min, $max)
        {
            $products = Product::whereBetween('price', [$min, $max])
                        ->get();
        
            dd($products);
        }
    }

Laravel's whereBetween function is really useful when you're dealing with a lot of data and you want to filter it down to what you require.

That's it for today. I hope it'll be helpful in upcoming project.