Aditya Banerjee
Aditya Banerjee

Reputation: 97

whereBetween passing a value and null

I have an eloquent query and I am passing a value and null in it. So for example if I have an price column and I have two variables $to and $from.

Example $from = 10 $to= ""

$from = 10;
$to = "";  
Product::whereBetween('price', [$from, $to])->get();

My question is that is this okay, will this work? If no then what shall I do if I want to search from 10 to infinity?

Upvotes: 1

Views: 1782

Answers (2)

Mahdi Abbariki
Mahdi Abbariki

Reputation: 11

you can use ?? in php for checking null values, so if the first value is empty, it will be equal the second value you've passed. like:

$from = $request->to ?? 0;
$to = $request->to ?? Model::max('column'); // names are imaginary

Upvotes: 1

yrv16
yrv16

Reputation: 2275

if $to can be empty value you should check it and build different queries depends on it.
For example:

$products = Product::query();

if(empty($to))
{
   $products = $products->where('price','>=', $from);
}
else 
{
   $products = $products->whereBetween('price', [$from, $to])
}

$products = $products->get();

Upvotes: 0

Related Questions