【发布时间】:2017-01-27 09:50:52
【问题描述】:
我正在尝试验证要通过表单插入到我的数据库中的文件。该文件应为“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;
}
验证方法:
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 行中的 ErrorException:参数 1 传递给 App\Services\QuoteService::validate() 必须是数组类型, 给定对象,调用 /var/www/html/Acadia/app/Services/QuoteService.php 在第 233 行和 定义
【问题讨论】:
-
请..发布您的方法代码
validate。它期待接收一个数组。但data是加载的 Excel 对象 -
公共函数 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);抛出$异常; } }
-
我认为问题在于您正在尝试使用验证器来验证 Excel 对象,但该验证器希望验证表单字段。你已经尝试过这种方式了吗? stackoverflow.com/questions/23625672/…
标签: php laravel validation csv maatwebsite-excel