between

How to use whereBetween Query in Laravel

Hello, Geek.In this post, I’ll go overusing whereBetween query in Laravel, which checks whether a column value is within a given range. I’ll show you some simple whereBetween() examples that we can use to filter our database records.

The following example shows how to use the Laravel eloquent method to perform Laravel whereBetween queries. The whereBetween() method will be used in the first example to limit our results to those that fall between two dates. In the following example, the OrderController will implement the recentOrders method. This method returns orders from the previous week.

Example 1: where between dates.

In the following code example, we will pass the two dates $from and $to to Laravel’s whereBetween() method to filter our records.

<?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);
    }
}

You can learn more about manipulating date using carbon like we have done in the example above from our tutorial: Laravel Carbon Add Days to Date with Example or Laravel Carbon Substract Days from Date with Example or Use Carbon to Get First and Last Day of Specific Month with Example

Example 2: where between values.

In the example below, we will use the number/decimal value to narrow our results. For the purposes of this example, I’ll use a ProductController to implement a filterProducts method that returns products based on 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);
        }
    }

In the preceding code example, we defined a method that accepts two arguments, $min and $max, and filters products based on these values. Laravel’s whereBetween method comes in handy when working with a large dataset and needing to filter it. Please leave any questions or suggestions for future posts in the comments section below.

All the best Nerds.

Leave a Reply