Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rdiyto's avatar

When importing Excel data, there is a transformDateTime error

I'm attempting to import Excel using the following code:

<?php

namespace App\Imports;
use Carbon\Carbon;
use App\Vch;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');

class VchImport implements ToModel, WithHeadingRow, WithBatchInserts, WithChunkReading
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */

    private function transformDateTime(string $value, string $format = 'd-m-Y')
    {
        try {
                return Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value))->format($format);
            } 
            catch (\ErrorException $e) 
            {
                return Carbon::createFromFormat($format, $value);
            }
    }
    
    public function model(array $row)
    {
        return new Vch([
            'no_vch' => $row[1],
            'nilai_vch' => $row[2],
            'batch' => $row[3],
            'expired' => $this->transformDateTime($row[4]),
            'nama_penerima' => $row[5],
            'alamat_penerima' => $row[6],
            'status' => $row[7],
        ]);
    }
}

When I try to import Excel, there is an error like this:

App\Imports\VchImport::transformDateTime(): Argument #1 ($value) must be of type string, null given, called in C:\Apache24\htdocs\gmpro-dev\app\Imports\VchImport.php on line 41

I've tried changing the date format via code, excel, and the computer still doesn't work. enter image description here

I'm debugging with dd($row); and get this result: row (4) it's supposed date:

array:10 [▼
  0 => null
  1 => "CP/WS-GADD/III/23-MR001799"
  2 => 100000
  3 => "0269"
  4 => 45366
  5 => null
  6 => null
  7 => "Beredar"
  8 => null
  9 => null
]
0 likes
6 replies
Snapey's avatar

you have to allow for the possibility of the row being empty by making the parameter optional, and then checking it in the function and returning empty string or default date

Also, the value is numeric not a string, but you type hint string in your function

rdiyto's avatar

@Snapey This code previously worked fine, before I moved to a new PC and upgraded to PHP 8 and Laravel 8. Is there anything I missed in the installation and upgrade?

rdiyto's avatar

@Snapey Could you please be more specific with a code or reference?

rdiyto's avatar
rdiyto
OP
Best Answer
Level 1

@Snapey My Excel is clean. No code and no formula. You know this error is due to my Excel format. I changed from .xlsx to .xls and it worked perfectly. Thank you for your attention.

Please or to participate in this conversation.