skip to Main Content

I have a laravel project and in this project there is a table like this:

enter image description here

I need to run a query and return a result where the $circulation variable is in range of the column range_from and range_to.

So I tried this:

$tariff = StoreCategoryTariff::where('option_value', $side)
      ->whereBetween('range_from', [$circulation, 'range_to'])
      ->orWhereBetween('range_to', [$circulation, 'range_from'])
      ->first()->price;

But this is wrong..

I also tried this one:

$tariff = StoreCategoryTariff::where('option_value', $side)
      ->where('range_from', '>=', $circulation)
      ->where('range_from', '<=', $circulation)
      ->first()->price;

But didn’t get the result. So how to properly check for the result where circulation is in range ?

4

Answers


  1. There’s no built-in method for this exact use case.

    I would recommend using a raw where:

    $tariff = StoreCategoryTariff::where('option_value', $side)
          ->whereRaw('? BETWEEN range_from AND range_to', [ $circulation ])
          ->first();
    

    This should get all rows where $circulation is contained between the range_from and range_to

    Login or Signup to reply.
  2. I think all you had to do was use the range_to instead of range_from again:

    $tariff = StoreCategoryTariff::where('option_value', $side)
    ->where('range_from', '<=', $circulation)
    ->where('range_to', '>=', $circulation)
    ->first();
    
    Login or Signup to reply.
  3. Try using nested where closure

    $tariff = StoreCategoryTariff::where('option_value', $side)
        ->where(function ($query) use ($circulation) {
            $query->whereBetween('range_from', [$circulation, 'range_to'])
                  ->orWhereBetween('range_to', [$circulation, 'range_from']);
        })
        ->first()->price;
    
    Login or Signup to reply.
  4. You should use >= for range_from and <= for range_to.
    You can try it. I think it will be solve your problem:

    $tariff = StoreCategoryTariff::where('option_value', $side)
          ->where('range_from', '>=', $circulation)
          ->where('range_to', '<=', $circulation)
          ->first()->price;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search