如何在规则层中添加条件?

时间:2017-11-25 15:17:33

标签: laravel laravel-5 request laravel-5.3 rules

我的控制器是这样的:

<?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个结果,具体取决于用户输入

如果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 个答案:

答案 0 :(得分:3)

有一个验证规则已经完成了这一点。 Laravel验证文档列出了所有可用的规则。

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

Laravel 5.3 - Docs - Validation - Rule - required if

答案 1 :(得分:0)

只需将验证更改为以下内容 -

2, 2

答案 2 :(得分:-1)

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

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