Laravel array sum of fields validation
Asked Answered
M

2

7

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?

Microscopic answered 15/7, 2018 at 13:3 Comment(1)
Take a look at this gist : gist.github.com/martinbean/b21e6bf5f5d75ffa9244b4bf530ea81eSemitropical
A
7

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');
        }
    });
}
Abolish answered 24/10, 2018 at 8:58 Comment(0)
C
5

I think it would be best for you to create a custom validation rule. In the validation, I'd convert the values array to a collection and use the collection sum method. E.g.:

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

    return $values->sum('percentage') <= 100;
}
Cece answered 15/7, 2018 at 14:8 Comment(3)
See this if you want to pass a parameter to passes(): laracasts.com/discuss/channels/laravel/…Schoof
gud idea, but why collect and sum, can't we use array_sum? any thoughts?Zippy
I did not test it, but array_sum might actually be faster than what I put in here back in 2018, since it does not require you to map the array set to a collection. So I think your suggestion is valid.Cece

© 2022 - 2024 — McMap. All rights reserved.