2016-09-19 83 views
1

我试图验证一个文件,我想通过窗体在我的数据库中插入。该文件应该是“csv”,其内容也要进行验证。Laravel:导入CSV - 验证

这里是处理表单控制器导入方法:

public function importFromCsv(array $data) { 
    if (Input::hasFile('import_file')) { 
     $path = Input::file('import_file')->getRealPath(); 

     $data = Excel::load($path, function($reader) { 
      //... 
     })->get(); 

     $this->validator = new QuoteValidator(); 

     $this->validate($data); 

     if (!empty($data) && $data->count()) { 

      foreach ($data as $key => $value) { 
       $insert[] = [ 
        'content' => $value->content, 
        'created_at' => $value->created_at, 
        'updated_at' => $value->created_at 
       ]; 
      } 

      if (!empty($insert)) { 
       DB::table('quotes')->insert($insert); 
      } 
     } 
    } 
    return true; 
} 

validate方法:

public function validate(array $data) { 
    $this->validator = Validator::make($data, $this->rules, $this->messages); 

    if ($this->validator->fails()) { 
     $exception = new InvalidDataException(); 
     $errors = $this->_parseMessages(); 
     $exception->setErrors($errors); 
     throw $exception; 
     } 
} 

我得到的错误:

ErrorException在QuoteService。 php行123:参数1传递到 App \ Services \ QuoteService :: validate()必须是类型数组,0123给定的对象,称为在 /var/www/html/Acadia/app/Services/QuoteService.php上线233和 定义

+0

请..post你的方法'validate'的代码。它期待收到一个数组。但数据是加载的Excel对象 – cmnardi

+0

public function validate(array $ data) $ this-> validator = Validator :: make($ data,$ this-> rules,$ this-> messages); ($ this-> validator-> failed()){ $ exception = new InvalidDataException(); $ errors = $ this - > _ parseMessages(); $ exception-> setErrors($ errors);抛出$ exception; ; } } –

+0

我认为问题在于你正在尝试使用验证器来验证Excel对象,但此验证程序期望验证表单域。你有没有试过这种方式? http://stackoverflow.com/questions/23625672/laravel-file-upload-validation – cmnardi

回答

0

要传递到validate方法变量是一个集合对象(Documentation ),但你的validate方法需要一个数组。

在将数据传递给validate方法之前,必须将其转换为数组。你可以做的是通过调用方法toArray()

例子:

$data = Excel::load($path, function($reader) { 
    //... 
})->get()->toArray(); 
+0

结果:调用你的if语句中的非对象 –

+0

的成员函数count()你调用$ data-> count() 。现在你的数据是一个数组。你必须改变它来计数($数据)。 – flipjms