2016-09-19 77 views
1

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

+0

請..post你的方法'validate'的代碼。它期待收到一個數組。但數據是加載的Excel對象 – cmnardi

+0

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; ; } } –

+0

我認爲問題在於你正在嘗試使用驗證器來驗證Excel對象,但此驗證程序期望驗證表單域。你有沒有試過這種方式? http://stackoverflow.com/questions/23625672/laravel-file-upload-validation – cmnardi

回答

0

要傳遞到validate方法變量是一個集合對象(Documentation ),但你的validate方法需要一個數組。

在將數據傳遞給validate方法之前,必須將其轉換爲數組。你可以做的是通過調用方法toArray()

例子:

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

結果:調用你的if語句中的非對象 –

+0

的成員函數count()你調用$ data-> count() 。現在你的數據是一個數組。你必須改變它來計數($數據)。 – flipjms