Laravel:导入CSV验证


Laravel: Importing CSV - validation

我试图验证一个文件,我想通过一个表单在我的数据库中插入。该文件应为"csv",其内容也要进行验证。

下面是控制器中处理表单的import方法:
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;
}
验证方法:
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;
        }
}

我得到的错误:

QuoteService.php第123行出错:参数1传递给App'Services'QuoteService::validate()必须是数组类型,给定对象,调用对象/var/ww/html/acadia/app/services/quoteservice .php第233行定义

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

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

的例子:

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