查询失败时不要停止循环。 LARAVEL

时间:2017-06-01 14:37:29

标签: php laravel

我将.csv文件上传到我的laravel应用程序中的控制器,控制器遍历文件的所有行并在我的数据库中创建新行。我工作得很好,但问题是,如果csv的一行有问题,循环将停止,网页将显示查询问题的错误(可能是csv文件中的任何错误)。但我想要的是,无论何时无法保存一行,控制器都会省略该行并继续使用下一行。这是我的控制器的功能:

 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);
        }

我也试过try catch,但我不太清楚如何正确使用它。

        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);

非常感谢,我将非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

不确定那是你做了什么,但试试这个

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);
    }

此外,如果文件出错,则不会是QueryException