Search code examples
phpdatetimebooleanlaravel-5.3

Call to a member function format() on boolean - Laravel


I am getting:

"Call to a member function format() on boolean in UploadController.php line 87"

This is row 58 to 93, with 87 being bold :

    set_time_limit(120);
    $now = (new \DateTime)->format('Y-m-d H:i:s');
    $nowYmd = (new \DateTime())->format('Y-m-d');
    foreach ($rows as $row) {
        $deviceLog = [];
        $deviceLog['installation_id'] = $this->parseForNull((int)$row[0]);
        $deviceLog['device_id'] = $devicesSerialToId[$row[1]];
        $deviceLog['2'] = $this->parseForNull($row[2]);
        $deviceLog['3'] = $this->parseForNull($row[3]);
        $deviceLog['4'] = $row[4];
        $deviceLog['5'] = $this->parseForNull($row[5]);
        $deviceLog['6'] = $this->parseForNull($row[6]);
        $deviceLog['7'] = $this->parseForNull($row[7]);
        $deviceLog['8'] = $this->parseBoolean($row[8]);
        $deviceLog['9'] = $this->parseBoolean($row[9]);
        $deviceLog['10'] = $this->parseBoolean($row[10]);
        $deviceLog['11'] = $this->parseForNull(intval($row[11]));
        $deviceLog['12'] = $this->parseForNull($row[12]);
        $deviceLog['13'] = $this->parseForNull($row[13]);
        $deviceLog['14'] = $this->parseForNull($row[14]);
        $deviceLog['15'] = $this->parseForNull($row[15]);
        $deviceLog['16'] = $this->parseForNull($row[16]);
        $deviceLog['17'] = $this->parseForNull($row[17]);
        $deviceLog['18'] = $this->parseBoolean($row[18]);
        $deviceLog['19'] = $this->parseBoolean($row[19]);
        $deviceLog['20'] = $this->parseForNull($row[20]);
        $deviceLog['21'] = $this->parseBoolean($row[21]);
        if (!empty($row[22])) {
            $date = \DateTime::createFromFormat('d-M-y', $row[22]);
            **if($date->format('Y-m-d') != $nowYmd) {**
                continue;
            }
            $deviceLog['last_seen'] = $date->format('Y-m-d');
        } else {
            continue;
        }

How do i fix this? The upload is a csv file and the date can either be null/blanc or is in the following format :23-jan-17. As you can see by the code, the data is not supposed to be put in the database if the last_seen date is not today.

Ideas? Running laravel.


Solution

  • check value of $row[22]. error will occurs if it is null.

    if (!empty($row[22])) {
            $date = \DateTime::createFromFormat('d-M-y', $row[22]);
            if(!$date || ($date && ($date->format('Y-m-d') != $nowYmd))) {
                continue;
            }
            $deviceLog['last_seen'] = $date->format('Y-m-d');
        } else {
            continue;
        }