Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
mrateb Avatar asked Jul 15 '18 13:07

mrateb


People also ask

How to validate form array in Laravel?

To validate a set of objects or the data in an array, Laravel avails of validation options of various kinds. You can consider all the options that are made available before finally sticking on to one of the options. Form array validation is one such process.

What are the benefits of ‘validation’ in Laravel?

Also, the benefit of creating a new rule and customizing it as per the needs is possible in ‘validation’ in Laravel. There are array-based forms that can be generated in Laravel and they are not a pain to be generated. The ‘dot notification’ can be used by the user to validate the attributes that are present within an array.

How do I validate a field in CodeIgniter using Laravel?

I’m migrating my site from Codeigniter to Laravel, in Codeigniter it’s much more easier. You just put ‘ []’ behind the field name, so just use ‘items []’ as the field name and the validation will work on array.

How do I add a new input field in Laravel?

In a real world scenario clicking the “Add New” button would load in a new input field with the field name being an array. All of that would happen with JavaScript and is beyond the scope of this tutorial however if you’d like to see a quick way of doing it have a look at this thread. To handle the actual validation Laravel gives us a few options.


1 Answers

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');
        }
    });
}
like image 153
doncadavona Avatar answered Sep 18 '22 11:09

doncadavona