Laravel array sum of fields validation

mra*_*teb 6 laravel laravel-validation

I'm new to Laravel where I'm using Laravel's validator for a project not built in Laravel.

I need to know if there is a simple built in Laravel validator to validate the sum of a certain field in all of the objects in an array.

My input looks something like:

{
    "customer":95,
    "name": "My object",
    "values":
        [
        { 
            "name": "AAA",
            "percentage": 50
        },
        {
            "name": "BBB",
            "percentage": 50
        }
    ]

}
Run Code Online (Sandbox Code Playgroud)

I need to make sure that the sum of my percentages is 100. Is there a simple way?

don*_*ona 6

使用自定义验证规则进行单属性验证。

使用After Validation Hook进行其他或更复杂的验证,比如多个字段的总和。

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->get('field1') + $this->get('field2') + $this->get('field3') != 100) {
            $validator->errors()->add(null, 'The sum of field1, field2 and field3 must be 100');
        }
    });
}
Run Code Online (Sandbox Code Playgroud)


jas*_*end 5

我认为您最好创建一个自定义验证规则。在验证中,我将 values 数组转换为集合并使用集合 sum 方法。例如:

public function passes($attribute, $value)
{
    $values = collect($value);

    return $values->sum('percentage') <= 100;
}
Run Code Online (Sandbox Code Playgroud)