skip to Main Content
$period = new DatePeriod(
    new DateTime('2024-03-20 00:00:00'),
    new DateInterval('P1D'),
    new DateTime('2024-03-28 23:59:59')
);
$suppliersInfo = OrderProduct::whereNotNull('brand')
        ->whereBetween('updated_at', [$startDate, $endDate ])->get();

$labels = [];

foreach ($period as $date){
          $labels[] = $date->format('d-m-Y');  
          $dateToSearch = $date->format('Y-m-d'); 
          $orderCount = $suppliersInfo->where( 'updated_at' , $dateToSearch ) 
         ->where('brand','nestle')
         ->count();
         $data[] = $orderCount;
}

As you see from the code above, I have a date information with just date but I need to search it in the database’s (postgresql) updated_at DateTime field. Because this field also has time info, I can’t find the date. I can set two dates from $dateToSearch with 00:00:00 and 23:59:59 time infos and use whereBetween but I’m not sure if it’s a suitable solution. Is there anything easier like we use whereDate at Eloquent?

By the way I can’t use DatePeriod::INCLUDE_END_DATE because of my PHP version.

2

Answers


  1. you can use DB::raw to apply the date function to your field.

    // assuming these have been validated to be a date in the "Y-m-d" format
    $startDate = $request->input('start');
    $endDate = $request->input('end');
    
    OrderProduct::query()
      ->whereNotNull('brand')
      ->whereBetween(DB::raw('DATE(updated_at)'), [$startDate, $endDate])
      ->get();
    
    Login or Signup to reply.
  2. did you use the whereDate method ?

    $period = new DatePeriod(
        new DateTime('2024-03-20 00:00:00'),
        new DateInterval('P1D'),
        new DateTime('2024-03-28 23:59:59')
    );
    
    $labels = [];
    $data = [];
    
    
    foreach ($period as $date){
        $labels[] = $date->format('d-m-Y');
        $dateToSearch = $date->format('Y-m-d');
    
        $orderCount = OrderProduct::whereNotNull('brand')
            ->whereDate('updated_at', $dateToSearch)
            ->where('brand', 'nestle')
            ->count();
        
        $data[] = $orderCount;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search