Laravel Excel maatwebsite validate spreadsheet before importing to database

Asked

Viewed 45 times

1

I am trying to validate a spreadsheet before importing it to the database, I need to check if there is any date above today’s date in the file, but I can only check the first line and there may be several dates on random lines. My import function in the controller:

public function Import(Request $request){
    $contador = 0;
    $today_carbon = Carbon::today()->toDateString();
    $request->validate(['arquivo'=>'required|mimes:csv']);
    $arquivo    = $request->file('arquivo');
    $planilha = Excel::toArray(new UserImport,$arquivo);
    foreach($planilha as $p){
        foreach($p as $i){
            $contador++;
            $colunas = count($i);
            $data = $i[2];
            if($today_carbon >= $data){
                Excel::import(new UserImport,$arquivo);
                return redirect('formulario')->with('sucesso','importação concluida');
            }else{
                return redirect('formulario')->with('erro','erro,não pode ter datas acima de hoje');
            }
            if($colunas == 3){
                Excel::import(new UserImport,$arquivo);
                return redirect('formulario')->with('sucesso','importação concluida');
            }else{
                return redirect('formulario')->with('erro','erro,estrutura incorreta');
            }
        }
    }
}

My import model:

    class UserImport implements ToModel{
    use Importable , SkipsErrors;

    
    public function model(array $row){
        
            return new User([
                'nome'    => $row[0], 
                'cpf' => $row[1],
                'data_venda' => $row[2]
            ]);  
    }

}

When I give a dd($planilha); the variable that transforms the worksheet into an array looks like this:

inserir a descrição da imagem aqui

I know it will take longer to import the spreadsheet by doing several more checks on files with more than 20k lines, but what is missing? this would be the best solution?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.