Laravel Excel上传和验证CSV在Validator上失败

时间:2019-03-28 12:08:15

标签: php laravel

我正在尝试上传CSV文件,并针对每一列的数据类型对其进行验证。我正在Laravel 5.8上使用Laravel-Excel 3.1

我允许用户上传CSV,因此该表是动态生成的。我为验证器(`$ this-> validator_array')建立了一个数组,如下所示:

array:6 [▼
  "*.0" => "date_format:d/m/Y|required"
  "*.1" => "integer"
  "*.2" => "date_format:d/m/Y"
  "*.3" => "string"
  "*.4" => "float|required"
  "*.5" => "string|required"
]  

然后在我的Import class使用集合导入中,我这样称呼它:

/**
 * Import CSV into collection
 *
 * @param Collection $rows
 */
public function collection(Collection $rows)
{
    // Use Laravel to validate
    Validator::make($rows->toArray(), [
        $this->validator_array
    ])->validate();

    foreach ($rows as $rowNum => $row)
    {
        // Only start import at desired row
        if ($rowNum >= $this->start_import_row) {

            // Format insert record
            foreach($row as $colNum => $col) {
                $this->formatted_row[$this->table_headings[$colNum]] = $col;
            }

            // Save record in table
            DB::table($this->table_name)->insert($this->formatted_row);

        }

    }
}

但是由于无法识别的验证而失败。我的讯息是:

Method Illuminate\Validation\Validator::validateNumeric|required does not exist.

我想念什么?

1 个答案:

答案 0 :(得分:1)

如果$this->validator_array已经是一个数组,则可以使用[$this->validator_array]将其嵌套在另一个数组中,因此只需尝试:

Validator::make($rows->toArray(), $this->validator_array)->validate();