Nom*_*man 6 php laravel laravel-5
我有一个表单将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',
]);
Run Code Online (Sandbox Code Playgroud)
在不对所有规则进行解释的情况下,应该确保该length字段总是null在type不存在时string或者decimal不能将长度分配给除这些类型之外的列.所以,我试图sometimes在$validator实例上使用该方法.
$validator->sometimes('structure.*.length', 'in:null', function ($input) {
// how to access the structure type here?
});
Run Code Online (Sandbox Code Playgroud)
我的问题是关闭,我该如何确保里面length是null只对具有数组元素type设置为比其他string或decimal.
我已经尝试过该dd函数,似乎整个输入数组都传递给了闭包.
$validator->sometimes('structure.*.length', 'in:null', function ($input) {
dd($input);
});
Run Code Online (Sandbox Code Playgroud)
这是dd方法的输出.
这是一个很好的问题。我查看了times()的 API 。看来,你想做的事,目前是不可能的。 一种可能的替代方案是使用After Validation Hook。例如:
Run Code Online (Sandbox Code Playgroud)
$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');
}
}
});