我在下面有验证规则
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中完成验证后,如何调用此代码块?
答案 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')])
);
};
}
}
}