我試圖驗證一個文件,我想通過窗體在我的數據庫中插入。該文件應該是「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