Laravel:导入 CSV - 验证

Laravel: Importing CSV - validation

我正在尝试验证要通过表单插入到我的数据库中的文件。该文件应该是 "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;
        }
}

我得到的错误:

ErrorException in QuoteService.php line 123: Argument 1 passed to App\Services\QuoteService::validate() must be of the type array, object given, called in /var/www/html/Acadia/app/Services/QuoteService.php on line 233 and defined

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

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

来做到这一点

示例:

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