laravellaravel-excel

How to Use Rules Date Validation in Laravel Excel


If input date in Excel doesn't use format, ex input string, I got the error

floor(): Argument #1 ($num) must be of type int|float, string given`

If using date format, it works fine, but when input doesn't use format date, I get the error.

How to handle this?

Here is my code

    public function collection(Collection $rows)
    {   
                
        foreach ($rows as $key => $row) {
            $izin = Izin::where('nama_izin', $row['id_izins'])->where('id_users', Auth::id())->pluck('id')->first();

            $customMessages = [
                $izin => 'Perhatikan ' . '"' . $row['id_izins'] . '"' . ' Pada baris ' . $key + 2 . ' tidak terdaftar',
            ];

            Validator::make($rows->toArray(), [
                $izin => 'required',
            ], $customMessages)->validate();
            
            LaporIzin::create([
                'nama_perusahaan' => $row['nama_perusahaan'],
                'alamat_perusahaan' => $row['alamat_perusahaan'],
                'tanggal_masuk' =>  Date::excelToDateTimeObject($row['tanggal_masuk']),
                'tanggal_izin' =>  Date::excelToDateTimeObject($row['tanggal_izin']),
                'nomor_izin' => $row['nomor_izin'],
                'id_izins' => $izin,
                'id_users' => Auth::id(),
            ]);

        }
    }

    public function rules(): array
    {
        return [
            'nama_perusahaan' => 'required',
            'nomor_izin' => 'required',
        ];
    }

How to handle using condition or any solution to this?


Solution

  • When date input is empty you can check for empty date , maybe it would help,

    'tanggal_masuk' => is_numeric($row['tanggal_masuk']) ? Date::excelToDateTimeObject($row['tanggal_masuk']) : null;