Search code examples
laravellaravel-validation

Laravel array sum of fields 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
        }
    ]

}

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


Solution

  • Use Custom Validation Rules for single attribute validations.

    Use After Validation Hook for other or more complex validations, say the sum of multiple fields.

    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');
            }
        });
    }