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' )
            );
            $orders = OrderProduct::where ('brand','<>','NULL');
            foreach ($period as $date){
                $labels[] = $date->format('d-m-Y'); 
                $searchDate = $date->format('Y-m-d');  **//This doesn't work**
                //$searchDate = '2024-03-26';          **//This works**
                $order = $orders->whereDate( 'updated_at','=',$searchDate )->get();
                foreach ($order as $item){
                    if( $item ){
                        Log::info( $item->brand );
                    }
                }
            }

As you see when I try //This works line. It works but when I use code like above it doesn’t work. I have checked $searchDate with gettype() and it shows string. My database postgresql and updated_at field like = 2024-03-26 09:17:01

2

Answers


  1. I think the issue arises from reusing the $orders query within the loop, causing it to modify the query builder state each iteration. Clone the query for each iteration or build a new query inside the loop to avoid this problem

    $period = new DatePeriod(
        new DateTime('2024-03-20 00:00:00'),
        new DateInterval('P1D'),
        new DateTime('2024-03-28 23:59:59')
    );
    
    $baseQuery = OrderProduct::where('brand', '<>', 'NULL');
    
    foreach ($period as $date) {
        $labels[] = $date->format('d-m-Y'); 
        $searchDate = $date->format('Y-m-d');  // This should work now
    
        // Clone the base query for each iteration
        $orders = clone $baseQuery;
        $order = $orders->whereDate('updated_at', '=', $searchDate)->get();
        
        foreach ($order as $item) {
            if ($item) {
                Log::info($item->brand);
            }
        }
    }
    
    Login or Signup to reply.
  2. It seems that the problem is with how the query is constructed inside the loop. In your code snippet, you are modifying the $orders instance directly inside the loop, it will persist the modifications of each iteration into next iteration.

    You should clone the instance of $order so each iteration use a fresh instance of the query.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search