2016-06-30 65 views
0

我有三種不同的形式提交給Laravel中的同一個控制器。每個表單都有自己的驗證規則存儲在請求中。這裏是我的代碼示例:Laravel演員請求不同請求

public function store($id, $type, Request $request) 
{ 
    switch ($type) { 
     case 'daily': 
      $this->monthly($id, $type, $request); 
      break; 
     case 'monthly': 
      $this->monthly($id, $type, $request); 
      break; 
     case 'yearly': 
      $this->yearly($id, $type, $request); 

    } 
    return redirect(route('x.show', $id)); 
} 


private function monthly($id, $type, MonthlyFormRequest $request) 
{ 
    //store form 
} 

然而,這並不因爲Request工作,throwns實例錯誤是不一樣的類型在monthly方法MonthlyFormRequest。有沒有辦法將Request轉換成MonthlyFormRequest還是有其他方法可以做到嗎?我寧願避免在控制器本身中聲明驗證規則。在商店方法中獲得統一的Request類型請求並使用MonthlyFormRequest的最佳方法是什麼?

回答

3

你可以傳遞型槽式請求參數,因此開關情況下,有移動到您的要求和預製品的檢查:

在您的要求:

public function rules() 
     { 
      switch($this->type){ 
      case 'dailty': 
        return [ 
          'field': 'required' 
         ]; 
        break; 
      case 'monthly': 
        return [ 
          'field': 'required' 
         ]; 
        break; 
      case 'yearly': 
        return [ 
          'field': 'required' 
         ]; 
        break; 
      } 

     } 

在你的控制器:

public function store($id, YourCustomRequest $request) 
{ 
    return redirect(route('x.show', $id)); 
}