I’m attempting to import Excel using the following code:
<?php
namespace AppImports;
use CarbonCarbon;
use AppVch;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsWithHeadingRow;
use MaatwebsiteExcelConcernsWithBatchInserts;
use MaatwebsiteExcelConcernsWithChunkReading;
use MaatwebsiteExcelImportsHeadingRowFormatter;
HeadingRowFormatter::default('none');
class VchImport implements ToModel, WithHeadingRow, WithBatchInserts, WithChunkReading
{
/**
* @param array $row
*
* @return IlluminateDatabaseEloquentModel|null
*/
private function transformDateTime(string $value, string $format = 'd-m-Y')
{
try {
return Carbon::instance(PhpOfficePhpSpreadsheetSharedDate::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:
AppImportsVchImport::transformDateTime(): Argument #1 ($value) must be of type string, null given, called in C:Apache24htdocsgmpro-devappImportsVchImport.php on line 41
I’ve tried changing the date format via code, excel, and the computer still doesn’t work.
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
]
3
Answers
My Excel is clean. No code and no formula. This error is due to my Excel format. I changed from
.xlsx
to.xls
and it worked perfectly. Thank you for your attention.the
model
method runs on every row of excel file . so when you get dd of rowthe result is belongs to first row of excel and maybe the problem is caused by another row .
the obvious cause of this error is that in one row of excel the 4th row is empty. so you need to handle this exception :
or another way:
You should handle this error by validating the rows by
WithValidation
concern. you can define rules, ex:By define this rules the $row[4] cannot be empty
With the
SkipsOnFailure
concern you get control over what happens the moment a validation failure happens by theonFailure
functionor just use the
SkipsFailures
trait.Your first row is empty, you should use the
WithStartRow
concern, and define the startRow function like this:With this the import begins from the second row, jumped out the empty row, or another solution
Handle in the code if the date is null, in this way you can avoid the error