I'm trying to load an excel file which contains dates as strings formatted as dd.mm.YYYY. I want to parse the excel file and save the values into the mysql database. I'm able to do this without an issue while creating a new entry into the database with a create form that has a selectable html date input in the form of:
<input type="date" id="expiry_date" class="form-control @error('expiry_date') is-invalid @enderror" name="expiry_date" value="" required autocomplete="expiry_date">
Below is the import function inside the controller that uses Maatwebsite's excel class.
public function import()
{
Excel::import(new excel_import(), storage_path('excel_file.xlsx'));
return redirect()->route('index');
}
This calls the excel_import class which is shown below:
public function model(array $row)
{
try
{
$date = Carbon::createFromFormat("d.m.Y", $row[5])->format('Y-m-d');
//$timestamp = strtotime($row[5]);
//$date = date("Y-m-d", $timestamp);
return new Item([
'user' => $row[0],
'name' => $row[1],
'expiry_date' => $date,
]);
}
catch(Throwable $t){
return null;
}
}
Note that the date variable I'm trying to enter is named expiry_date. I've tried getting the date format from Carbon and from the timestamp(as in the comments) but to no avail. In the model I've tried setting it as:
public $casts = ['expiry_date' => 'date:Y-m-d',];
public $dates = ['expiry_date',];
Also note I've set up the expiry_date variable as follows in the migration:
$table->date('expiry_date')->nullable();
I also used dd in the create form and in the excel_import class which showed but variables were Carbon datetime instances. The result is a null field for the expiry_date variable. If I don't set expiry_date as nullable it returns an error SQLSTATE[HY000]: General error: 1364 Field 'expiry_date' doesn't have a default value. I'm truly stumped, any help would be appreciated.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire