【问题标题】:Laravel: Importing CSV - validationLaravel:导入 CSV - 验证
【发布时间】: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


【解决方案1】:

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

在将数据传递给验证方法之前,您必须将其转换为数组。你可以通过调用toArray()方法来做到这一点

例子:

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

【讨论】:

  • 结果:在非对象上调用成员函数 count()
  • 在 if 语句中调用 $data->count()。现在您的数据是一个数组。您必须将其更改为 count($data)。
猜你喜欢
  • 2016-11-28
  • 2020-10-29
  • 2019-12-29
  • 2011-03-14
  • 2018-11-18
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多