2017-11-25 176 views
0

我的控制器是这样的:如何在规则laravel中添加条件?

<?php 
use App\Http\Requests\StoreReceiveOrderRequest; 
class SellController extends Controller 
{ 
    public function receiveOrder(StoreReceiveOrderRequest $request) 
    { 
     dd($request->all()); 
     ... 
    } 
} 

之前在receiveOrder方法执行的语句,它会检查在StoreReceiveOrderRequest

规则

的StoreReceiveOrderRequest这样的:

<?php 
namespace App\Http\Requests; 
use Illuminate\Foundation\Http\FormRequest; 
class StoreReceiveOrderRequest extends FormRequest 
{ 
    public function rules() 
    { 
     return [ 
      'is_follow_up'=>'required', 
      'note'=>'max:300' // I want to make this to be required if is_follow_up = n 
     ]; 
    } 
} 

dd($request->all());的结果,有2个结果,取决于用户输入

如果t他is_follow_up = Y,结果是这样的:

Array 
(
    [is_follow_up] => y 
) 

如果is_follow_up = N,结果是这样的:

Array 
(
    [is_follow_up] => n 
    [note] => test 
) 

如果is_follow_up = N,我想要做的音符需要

如果is_follow_up = Y,不需要注

似乎它必须在规则上添加条件

我该怎么做?

回答

3

有所做的正是这已经是一个验证规则。 Laravel验证文档列出了所有可用的规则。

'note' => 'required_if:is_follow_up,n|...' 

Laravel 5.3 - Docs - Validation - Rule - required if

+0

似乎你可以帮助我。看这个。 https://stackoverflow.com/questions/47726407/how-can-i-add-condition-based-on-the-parameters-of-the-array-data-on-the-rules-l。这有点不同 –

0

只要改变你的验证就以下

<?php 
namespace App\Http\Requests; 
use Illuminate\Foundation\Http\FormRequest; 
    class StoreReceiveOrderRequest extends FormRequest 
    { 
     public function rules() 
     { 
     $rules = ['is_follow_up'=>'required', 
      ]; 

     if (Input::get('is_follow_up')=='n') { 
      $rules += [ 
      'note'=>'max:300' 
      ]; 
     } 
     } 
    } 
-1

阅读Laravel文档的所有可用的验证规则列表。

'note' => 'required_if:is_follow_up,n|...' 
+0

似乎你可以帮助我。看这个。 https://stackoverflow.com/questions/47726407/how-can-i-add-condition-based-on-the-parameters-of-the-array-data-on-the-rules-l。这有点不同 –

+0

@akramwahld我真的不明白什么是发布相同的答案,已经在这里... 2天后 – lagbox

+0

@lagbox,它不关你的业务,我可以随时回答任何问题,我可以,而且很明显我没有违反SO规则, –

相关问题