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

Laravel validator after method running before the 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 中验证完成后如何调用此代码块?

尝试写成

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')])
           );
       };
    }
  }
}