I am uploading a .csv file to a controller in my laravel application, and the controller loops through all the rows of the file and create new rows in my database. I works pretty well, but the problem is that if one of the rows of the CSV has a problem, the loop will be stopped and the web page will show the error with the query problem (that can be whatever was wrong in the CSV file). But what I want, is that whenever one row can’t be saved, the controller omits that row and keep working with the next ones. This is the function of my controller:
public function submit_file(Company $company, Request $data) { $this->validate($data, [ 'csvfile' => 'required' ]); $path = $data-> csvfile ->path(); $file = fopen($path,"r"); $num=1; $errors=[]; while(!feof($file)){ $job = New Job(); $line=""; $line=fgetcsv($file, 0, ";"); $job->city=$line[1]; $job->id_position =intval($line[2]); // and so on .. if(!$company->jobs()->save($job)){ $errors.push(array("Line # $num" => "The line # $num of the CSV file could not be uploaded“)); } $num++; } return back()->withErrors($errors); }
I have also tried with the try catch but I’m not quite sure of how to use it correctly.
try { $company->jobs()->save($job); } catch(Exception $e){ array_push($errors,"The line # $num of the CSV file could not be uploaded. Error: " . $e->getMessage()); } return back()->withErrors($errors);
Thanks a lot, I will totally appreciate any help.
Advertisement
Answer
Not sure if thats what you did but try this
public function submit_file(Company $company, Request $data) { $this->validate($data, [ 'csvfile' => 'required' ]); $path = $data-> csvfile ->path(); $file = fopen($path,"r"); $num=1; $errors=[]; while(!feof($file)){ try { $job = New Job(); $line=""; $line=fgetcsv($file, 0, ";"); $Job->city=$line[1]; $Job->id_position =intval($line[2]); // and so on .. if(!$company->jobs()->save($job)){ $errors.push(array("Line # $num" => "The line # $num of the CSV file could not be uploaded")); } $num++; } catch(Exception $ex) { $errors . push(array("Line # $num" => "The line # $num of the CSV file could not be uploaded. Error: $ex->getMessage() ")); } } return back()->withErrors($errors); }
Also, if its something wrong with the file, it would not be QueryException