Tanmay
Tanmay

Reputation: 3159

whereBetween not working with dates as expected

I have a query like this:

App\Model::where('some', 'condition')->orWhere('some', 'other_condition')->whereBetween('created_at', [request('from'), request('to')])->get();

Why the whereBetween clause not working here? Instead of returning the records between the provided dates, it returns all the records.

Here are the request params:

from: 2018-08-14
to:   2018-08-09

What am I missing?

Upvotes: 0

Views: 217

Answers (2)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

As your query

App\Model::where('some', 'condition')->orWhere('some', 'other_condition')->whereBetween('created_at', [request('from'), request('to')])->get();

It was like below query

SELECT * FROM `table` WHERE `some` = 'text' OR `some` = 'other_text' AND `created_at` BETWEEN 'from' AND 'to'

So from this query it will return all data which was having some = text or some = other text

you need to make query like below

SELECT * FROM `table` WHERE (`some` = 'text' OR `some` = 'other_text') AND `created_at` BETWEEN 'from' AND 'to'

So it will check for between date and text

You should try This:

App\Model::whereRaw('some = condition OR some = other_condition')->whereBetween('created_at', [request('from'), request('to')])->get();

Upvotes: 1

Alexandru Petrescu
Alexandru Petrescu

Reputation: 3479

I think this is doing:

select from blah where some=condition or some=other_condition and created_at between date1 AND date2. 

You can run DB::enableQueryLog(); before the query then print_r(DB::getQueryLog()); to see the actual query that's being run.

Might want to try

App\Model::
  whereBetween('created_at', [request('from'), request('to')])
  ->where(function($query) { 
     $query
     ->where('some', 'condition')
     ->orWhere('some', 'other_condition')
   })->get();

I think that'll do

select from blah where created_at between date1 AND date2 and (some=condition or some=other_condition). 

Upvotes: 1

Related Questions