在验证之前运行方法之后的Laravel验证器

时间:2019-11-12 16:12:36

标签: laravel laravel-validation

我在下面有验证规则

public function rules()
{
    return [
        'ports' => 'required|array|min:2|max:10',
        'ports.*.id' => 'required|distinct|exists:ports,id',
        'ports.*.order' => 'required|distinct|integer|between:1,10',
    ];
}

和withValidator方法

public function withValidator($validator)
{
    // check does order numbers increasing consecutively
    $validator->after(function ($validator) {
        $orders = Arr::pluck($this->ports, 'order');
        sort($orders);

        foreach ($orders as $key => $order) {
            if ($key === 0) continue;

            if ($orders[$key - 1] + 1 != $order) {
                $validator->errors()->add(
                    "ports.$key.order",
                    __('validation.increase_consecutively', ['attribute' => __('validation.attributes.order')])
                );
            };
        }
    });
}

如果客户端未发送ports数组,则Arr:pluck方法将引发异常,因为$this->ports等于NULL。在formRequest中完成验证后,如何调用此代码块?

1 个答案:

答案 0 :(得分:1)

尝试用

书写
if ($validator->fails())
{
    // Handle errors
}

例如。

public function withValidator($validator)
{
  if ($validator->fails())
  {
    $orders = Arr::pluck($this->ports, 'order');
    sort($orders);

    foreach ($orders as $key => $order) {
       if ($key === 0) continue;

       if ($orders[$key - 1] + 1 != $order) {
           $validator->errors()->add(
               "ports.$key.order",
               __('validation.increase_consecutively', ['attribute' => __('validation.attributes.order')])
           );
       };
    }
  }
}