Home > Enterprise >  Laravel date time condition not working properly
Laravel date time condition not working properly

Time:02-01

I have two columns in my offer table as follow, I want to fetch those offer's record which is currently active:

offer_start_date offer_end_date
24-10-2022 10:57:00 24-10-2023 10:57:00

Below is my query date condition working fine but time is giving problems:

$now = Carbon::now();
$today = $now->toDateString();
$currentTime = $now->toTimeString();
$offers_data = Offer::whereRaw("offer_status=2 and offer_type=1 and is_special_offer=3")
->whereDate('offer_start_date','<=',$today)
->whereTime('offer_start_date','<=',$currentTime)
->whereDate('offer_end_date','>=',$today)
->whereTime('offer_end_date','>=',$currentTime)    
->limit(10)      
->get();

What would be the reason?

added screenshot of records

CodePudding user response:

Using whereDate and whereTime together is likely not working the way you think it is.

Instead, try just using where() and Laravel will work it out for you.

$now = Carbon::now();

$offers_data = Offer::whereRaw("offer_status=2 and offer_type=1 and is_special_offer=3")
    ->where('offer_start_date', '<=', $now)
    ->where('offer_end_date', '>=', $now)    
    ->limit(10)      
    ->get();

CodePudding user response:

I think the problem inside the date variables.

Replace your varibles with this varibles and check the result:

$now = Carbon::now();
$today = $now->toDateString();
$currentTime = $now->toTimeString();

to

$now = Carbon::now();
$today = $now->copy()->toDateString();
$currentTime = $now->copy()->toTimeString();
  • Related