kunal
kunal

Reputation: 4248

WhereBetween not working in laravel 5.2

I am using laravel framework but in this WhereBetween not working. i am using price range where price starts form 1 to 500. when i set price 1-100 it gives me all the records that is in beetween 1 to 100 i.e. 20,40,50 etc. When i change the value from 1- 150 the above result will not be displayed it gives me no result(20,40,50). Can anyone help me . Here is my Code

enter code here

     $products = Product::with("productimages")
                ->whereBetween('price',[$data['from'], $data['to']])
                 ->get();

Note:- $data['from'] start value i.e 1 and $data['to'] end value i.e 150 or more

Upvotes: 3

Views: 5185

Answers (2)

djboris
djboris

Reputation: 180

I just had the same issue. When the data type of the value is not an integer, it will behave very unpredictably. So the solution is to either change the datatype of the column or cast it while fetching, like this:

$from = $data['from'];
$to = $data['to'];

$products = Product::with("productimages")
    ->whereRaw("CAST(price AS UNSIGNED) BETWEEN ${from} AND ${to}")
    ->get();

I actually had this issue on the PostgreSQL jsonb data type, as it always returns nested values as strings, and between fetching doesn't work properly.

Upvotes: 1

channasmcs
channasmcs

Reputation: 1156

Using Where Between

$projects = Product::where('created_at', '>', $data['from'])
->where('created_at', '<', $data['to'])    
->get();

OR

  $current = Product::with("productimages")
  ->whereBetween('created_at', array($data['from'], $data['to']))->get();

OR

       DB::table('Product')->whereBetween('created_at', array($data['from'], $data['to']))->get();

Upvotes: 0

Related Questions