0

在我的控制器中,我有一个store验证请求数据的方法:

$request->validate([
    'title' => 'required',
    'description' => 'required',
    'date' => [
        'required',
        new DateFormatRule
    ],
    'closed' => 'nullable',
    'time_start' => 'required_if:closed,0',
    'time_end' => [
        'required_if:closed,0',
        new TimeDurationRule($request->time_start)
    ],
]);

closed是一个布尔值。如果closed为 false,则time_starttime_end字段是必需的。这似乎按预期工作。

但是,如果我提交一个closed真实的请求,我就会陷入我的习惯TimeDurationRule

'time_end' => [
    'required_if:closed,0',
    new TimeDurationRule($request->time_start)
], 

我怎样才能new TimeDurationRule($request->time_start)有条件?例如,如果closed为真,我手动设置time_endnull所以time_start/time_end不需要值(不需要)。

如果我将我的自定义排除注释掉,一切都会按预期进行。

感谢您的任何建议!

4

1 回答 1

1

您可以传递$request->closed给您TimeDurationRule,然后在 的passes方法中rule,您可以执行以下操作:

class TimeDurationRule implements Rule
{
    public $closed;

    public function __construct(/*all needed parameters*/, $closed)
    {
        $this->closed = $closed;
    }

    public function passes($attribute, $value)
    {
        if(!$closed){ 
         return true
        }

        // the rest of validation logic
    }
}

接着

new TimeDurationRule(/*all needed parameters*/, $request->closed)

您也可以在这里阅读更多相关信息:https ://laracasts.com/discuss/channels/laravel/create-custom-validation-rule-with-additional-parameters-implement-in-request

希望能帮助到你!

于 2020-03-19T21:46:36.193 回答