0

I'm working on a Laravel project and one of the feature is to load CSV/Excel files into a table. To do this I'm using Laravel-Excel package (https://docs.laravel-excel.com/3.1/imports/).

I successfully managed to load CSV files, but I have a problem with Excel files, in particular with the date validation. Basically the validation always tells me that the date is not a date (but it actually is), I tried with different formats but nothing changes.

This is my code:

OrdinanzaImport.php (this is the model import)

class OrdinanzaImport implements ToModel, WithValidation, WithHeadingRow
{
    public function model(array $row)
    {
        return new Ordinanza([
            'numero_verbale' => $row['numero_verbale'],
            'data_verbale'   => $row['data_verbale'],    ////here is the date field
            'cognome'        => $row['cognome'],
            'nome'           => $row['nome'],
            'codice_fiscale' => $row['codice_fiscale'],
            'citta'          => $row['citta'],
            'provincia'      => $row['provincia'],
            'data_notifica'  => $row['data_notifica'],
        ]);
    }

    public function rules(): array
    {
        return [
            'numero_verbale' => 'required|numeric|unique:ordinanze',
            'data_verbale'   => 'required|date:ordinanze',            ////here is the date validation
            'cognome'        => 'required|min:1|max:50:ordinanze',
            'nome'           => 'required|min:1|max:50:ordinanze',
            'codice_fiscale' => 'nullable|alpha_num|size:16:ordinanze', 
            'citta'          => 'required|min:1|max:50:ordinanze',
            'provincia'      => 'nullable|min:1|max:50:ordinanze',
            'data_notifica'  => 'nullable|date:ordinanze',
        ];
    }


controller.php

Excel::import(new OrdinanzaImport, $request->file('file'), null, \Maatwebsite\Excel\Excel::XLSX);


I also tried to use the following code that I found on the package issues but nothing:

'data_verbale' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['data_verbale']),

This is the Excel file if you want to check: https://filebin.net/yhuuhqb579g3qyle

How could this be fixed?

Thanks!

miken32
  • 42,008
  • 16
  • 111
  • 154
nicoblue
  • 71
  • 2
  • 13

1 Answers1

-1

The excel date being imported is an int datatype. Look into creating a custom rule in Laravel, this will be a class that implements the Rule interface. You could evaluate the PhpOffice date conversion in the rule and post a custom error message.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 08 '23 at 04:53