Using whereBetween Query in Laravel 8

Laravel 8 whereBetween Query

In this post, I will be going through Laravel Eloquent’s whereBetween() method which verifies that a column value is between a given range. I will be sharing some very simple
whereBetween() examples using this method to filter down our database records.

The below example will show you how to perform Laravel whereBetween queries with the Laravel eloquent method.

Example 1

In the first example, we will use the whereBetween() method to filter down our records between two given dates.

In the below example, we have a OrderController which will implement the recentOrders method. This method will return the orders placed in the last 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 above code example, we passed the two dates $from and $to to whereBetween() method of Laravel to filterdown our records.away

Example 2

In the next example, we will use the number/decimal value to filter down our records. For the sake of this example, I have a ProductController which will implement a filterProducts, this method will be responsible for returning the products based on a min and max 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 above code exmaple, we created a method which will take two arguments $min, $max and filter down products based on this price range.

Laravel’s whereBetween method is very handful when you are working with a large dataset for filtering it to your needs.

If you have any questions or suggestions for a post topic, please let us know in the comments box below.

Your little help will keep this site alive and help us to produce quality content for you.