我试图验证一个文件,我想通过窗体在我的数据库中插入。该文件应该是“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和 定义
请..post你的方法'validate'的代码。它期待收到一个数组。但数据是加载的Excel对象 – cmnardi
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; ; } } –
我认为问题在于你正在尝试使用验证器来验证Excel对象,但此验证程序期望验证表单域。你有没有试过这种方式? http://stackoverflow.com/questions/23625672/laravel-file-upload-validation – cmnardi