我有一个表单,该表单以数组形式发布了structure
字段。 structure
数组包含数据库表列的定义。
$validator = Validator::make($request->all(), [
'structure' => 'required|array|min:1',
'structure.*.name' => 'required|regex:/^[a-z]+[a-z0-9_]+$/',
'structure.*.type' => 'required|in:integer,decimal,string,text,date,datetime',
'structure.*.length' => 'nullable|numeric|required_if:structure.*.type,decimal',
'structure.*.default' => '',
'structure.*.index' => 'required_if:is_auto_increment,false|boolean',
'structure.*.is_nullable' => 'required_if:is_auto_increment,false|boolean',
'structure.*.is_primary' => 'required_if:is_auto_increment,false|boolean',
'structure.*.is_auto_increment' => 'required_if:structure.type,integer|boolean',
'structure.*.is_unique' => 'required_if:is_auto_increment,false|boolean',
'structure.*.decimal' => 'nullable|numeric|required_if:structure.*.type,decimal|lt:structure.*.length',
]);
在不解释所有规则的情况下,应确保当length
不是null
或{{时,type
字段始终为string
1}},因为您不能为这些类型以外的其他列分配长度。因此,我尝试在decimal
实例上使用sometimes
方法。
$validator
我的问题是在闭包内部,如何确保$validator->sometimes('structure.*.length', 'in:null', function ($input) {
// how to access the structure type here?
});
仅对于length
设置为null
以外的数组元素为type
或string
。
我尝试了decimal
函数,似乎整个输入数组都传递给了闭包。
dd
这是$validator->sometimes('structure.*.length', 'in:null', function ($input) {
dd($input);
});
方法的输出。
我可以使用dd
构造,但是效率不高吗?检查所有元素中的单个元素?
如何仅检查所考虑的数组元素的类型?
有Laravel方法可以做到吗?
答案 0 :(得分:0)
这是一个很好的问题。我看了sometimes()的API。您目前似乎无法执行您想做的事情。
一种可能的替代方法是使用验证钩后。例如:
$validator->after(function ($validator) {
$attributes = $validator->getData()['structure'];
foreach($attributes as $key => $value) {
if(! in_array($value['type'], ['string', 'decimal']) && ! is_null($value['length'])) {
$validator->errors()->add("structure.{$key}.length", 'Should be null');
}
}
});
答案 1 :(得分:0)
相反的想法怎么样?如果类型为字符串或十进制,则“长度”字段将变为必填。
events.js:187
throw er; // Unhandled 'error' event
^
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented
at Readable._read (_stream_readable.js:647:24)
at Readable.read (_stream_readable.js:490:10)
at maybeReadMore_ (_stream_readable.js:634:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on Readable instance at:
at errorOrDestroy (internal/streams/destroy.js:108:12)
at Readable._read (_stream_readable.js:647:3)
at Readable.read (_stream_readable.js:490:10)
at maybeReadMore_ (_stream_readable.js:634:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
code: 'ERR_METHOD_NOT_IMPLEMENTED'