2016-06-30 7 views
0

Laravelの同じコントローラに送信する3つの異なるフォームがあります。各フォームには、リクエストに格納された独自の検証ルールがあります。ここに私のコードの例です:Laravel cast別のリクエストに依頼する

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 
} 

Requestmonthly方法でMonthlyFormRequestと同じタイプではありませんので、しかし、これはインスタンスのエラーを仕事とthrownsしません。 RequestMonthlyFormRequestにキャストする方法はありますか、それを行うには別の方法がありますか?私は、コントローラ自体にバリデーションルールを宣言しないことを好む。ストアメソッドで均一な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)); 
} 
関連する問題