junmingyeo98
junmingyeo98

Reputation: 69

PHP Laravel How to get an array of dates for leaves duration

Hi I am trying to get an array of leave dates from my Leave table. I want to be able to get the dates from the start_date to end_date column of each row of leave data I have in 'Y-m-d' format in order to compare with my getDays method whichis in 'Y-m-d' format.

Below is the method I currently have in my controller class:

private function getLeaves()
    {
        $leavesList = Leave::where('clinic_id', '=', $_SESSION['clinic_ID'])->get();
        $leavesArray = json_decode($leavesList, true);
        
        foreach($leavesArray as $leave){
            //Convert each data from table to Y-m-d format to compare
            $leaves[] = CarbonPeriod::create(date('Y-m-d', strtotime($leave['start_date'])), date('Y-m-d', strtotime($leave['end_date'])));
            
        }
        return $leaves;
        
    }

Currently the output is this:

[["2021-05-20T16:00:00.000000Z"],["2021-05-06T16:00:00.000000Z","2021-05-07T16:00:00.000000Z"]]

Upvotes: 0

Views: 346

Answers (1)

Freeman
Freeman

Reputation: 71

Your problem is that the function CarbonPeriod::create() returns a period object. If you want to get each day in this period, you need to iterate in this period and format your date.

public function getLeaves()
{
    $leavesList = Leave::where('clinic_id', '=', $_SESSION['clinic_ID'])->get();
    $leavesArray = json_decode($leavesList, true);

    foreach($leavesArray as $leave){
        //Convert each data from table to Y-m-d format to compare
        $days = CarbonPeriod::create(
            date('Y-m-d', strtotime($leave['start_date'])),
            date('Y-m-d', strtotime($leave['end_date'])));

        foreach ($days as $day) {
            $leaves[] = $day->format('Y-m-d');
        }
    }
    return $leaves;

}

Upvotes: 1

Related Questions