2016-12-06 72 views
0

我有輸入表單,用戶在其中選擇項目的細節數量作爲他的預訂。例如:朱莉婭的預購:飲料 - 水1瓶,牛奶1杯,防彈咖啡1杯。Laravel 5.1。索引數組的驗證

@foreach ($item->detail()->orderBy('sequence')->get() as $detail) 
<td><input name="estimate_quantity[]"></td> 
@endforeach 

我想驗證我的數量,只有整數大於零或等於它。 所以我做了規則

public function rules() 
{ 
     $rules = [ 
      'estimate_quantity' => 'required|array', 
     ]; 
     $estimate_quantity = $this->request->get('estimate_quantity'); 
     foreach ($estimate_quantity as $index => $value){ 
      $rules["estimate_quantity.$index"] = 'integer|min:0'; 
     } 
     return $rules; 
} 

它不工作。如果我輸入字母字符,這將是一個錯誤

ErrorException in helpers.php line 468: 
htmlentities() expects parameter 1 to be string, array given 

1.什麼是正確的方式來做這種驗證?使它在控制器中看起來不太好。

2.如果我將我的自定義規則在單獨的文件中,哪裏更好地存儲它?創建應用程序/驗證文件夾?

3.規則執行後和控制器方法執行之前發生了什麼魔術?

我在Laravel和編程方面很新,對不起這個簡單的問題。

+0

你爲什麼不使用Laravel驗證? https://laravel.com/docs/5.3/validation#validation-quickstart –

+0

@Chonchol Mahmud我使用它。我有我的驗證邏輯與控制器分開,https://laravel.com/docs/5.1/validation#form-request-validation。 – Nikita

回答

0

我想你可以給數組元素,而不是.符號使用數組索引符號下面的應該工作

public function rules() 
{ 
     $rules = [ 
      'estimate_quantity' => 'required|array', 
     ]; 
     $estimate_quantity = $this->input('estimate_quantity'); 
     foreach ($estimate_quantity as $index => $value){ 
      $rules["estimate_quantity[".$index."]"] = 'integer|min:0'; 
     } 
     return $rules; 
} 
+0

你的方法更好,它不會導致ErrorException。謝謝!不幸的是,它不會返回驗證錯誤,因此控制器的方法將被評估。 – Nikita