Reputation: 737
I create excel import function and it working fine until I notice the date is not inserted properly, so I try to format the date like Y-m-d
to store properly in MySql, but the carbon gives below error
Carbon\Exceptions\InvalidFormatException
Unexpected data found. Unexpected data found. Trailing data
In excel I may have d/m/Y
or Y/m/d
so I want to format to tored in DB
My Import code
public function model(array $row)
{
return new Staff([
'employee_no' => $row['id'],
'name' => $row['name'],
'address' => $row['address'],
'fathers_name' => $row['father'],
'dob' => $this->transformDate($row['dob']),
'blood_group' => $row['blood_group'],
'phone' => $row['phone'],
'password' => Hash::make($row['id']),
]);
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
My Staff Model
class Staff extends Authenticatable
{
protected $fillable = [
'name', 'employee_no', 'designation_id', 'fathers_name', 'dob', 'identification_mark', 'blood_group', 'phone', 'address', 'height', 'rfid_no', 'building_id', 'password',
];
protected $casts = ['dob'];
}
What is the correct way, or do I have to approach the new format
for dob
Upvotes: 1
Views: 2984
Reputation: 77
Carbon::createFromFormat($format, $time)
should receive the format of the given $time
, not the format you want to convert to. Try changing it to $format = 'd/m/Y'
, as you said to be the format you expect to get from the records.
After that, you can get the database format just by making ->toDateString()
or ->toDateTimeString()
on the Carbon object.
See also:
Upvotes: 1