Laravel:当输入是数组时,使用验证器的有时方法

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字段总是nulltype不存在时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)

我的问题是关闭,我该如何确保里面lengthnull只对具有数组元素type设置为比其他stringdecimal.

我已经尝试过该dd函数,似乎整个输入数组都传递给了闭包.

$validator->sometimes('structure.*.length', 'in:null', function ($input) {
    dd($input);
});
Run Code Online (Sandbox Code Playgroud)

这是dd方法的输出.

输出<code>foreach</code>构造但不会效率低下吗?检查单个元素的所有元素?</p>

<p>如何仅检查所考虑的数组元素的类型?</p>

<p>是否有Laravel方法来做到这一点?</p></p>
    </div>
  </div>

<div class=

Moz*_*mil 0

这是一个很好的问题。我查看了times()的 API 。看来,你想做的事,目前是不可能的。

一种可能的替代方案使用After Validation Hook。例如:

$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');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)