有一个请求,其结构如下:
{
"anything": false,
"specifications": [
{
"nomenclature_id": null,
"nomenclature_name": "Деревянный камень",
"anything": true,
},
{
"nomenclature_id": 3, // !!!
"nomenclature_name": null,
"anything": true,
},
]
}
有必要描述联合现场验证的规则
specifications.*.nomenclature_id
specifications.*.nomenclature_name
以这样一种方式,其中一个必须为 null,另一个 !== null,同时:
如果 nomenclature_id !== null,则检查是否存在:nomenclatures,id
如果 nomenclature_name !== null,则检查字符串
我使用 required_if、exclusion_if 等规则尝试了不同的选项,有时等等。但没有达到预期的效果。很明显,我可以聪明地从控制器中删除此检查,并用代码描述它,但恕我直言,如果可以使用框架的内置工具完成某些操作,那么应该使用框架的工具来完成。
PHP 8.2
拉拉维尔 10
我解决了你的问题。我以自己的方式实现了以您的格式接收数据(有点悲伤)但这是为了清楚起见。
无论我在视图中看到什么,我们都会假设规格数组已正确到达,就像您的一样。
public function form(Request $request) { $request['specifications'] = [ [ "nomenclature_id" => null, "nomenclature_name" => "木石", "anything" => true, ], [ "nomenclature_id" = > 3, "nomenclature_name" => null, "anything" => true, ] ];
创建验证器 php artisan make:rule TestNull
class TestNull Implements ValidationRule { /** * 运行验证规则。 * * @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mix $value, Closure $fail): void { if(!is_null($value['nomenclature_id') ]) && is_null($value['nomenclature_name'])) { $rules = ['nomenclature_id' => 'exists:posts,id'];验证器::make($value, $rules)->passes(); }elseif (is_null($value['nomenclature_id']) && !is_null($value['nomenclature_name'])){ $rules = ['nomenclature_name' => 'string'];验证器::make($value, $rules)->passes(); } else { $fail('问题'); }
}
我按照我的理解提出了条件。您还需要阅读如何正确发出错误的信息。
使用:
nullable对于可以是的字段null;required_if对于当另一个字段具有特定值时必须必需的字段。根据听起来的选项,我整理了一份工作汇编。首先,创建自定义验证规则:
规则/规范/IdXorName.php
HTTP/请求/SpecificationRequest.php: