Home > Blockchain >  How can I validate the sum of the values in Laravel?
How can I validate the sum of the values in Laravel?

Time:11-30

I have 3 input tag with type number in blade.php. I want to validate the sum is equal to 100. So, how to do that? Thanks for your help.

Blade.php

<input type="number" name="number1" />
<input type="number" name="number2" />
<input type="number" name="number3" />

Controller

 public function store(Request $request) {
    $data = $request->validate([
       'number1' => 'required',
       'number2' => 'required',
       'number3' => 'required',
    ]);
    $sum = $data['number1']   $data['number2']   $data['number3'];
    $myDb = new Mynumber();
    $myDb->number1 = $data['number1'];
    $myDb->number2 = $data['number2'];
    $myDb->number3 = $data['number3'];
    $myDb->save();
 }

CodePudding user response:

If you want to stay within the boundaries of Laravels validator, I'd suggest you either use the after validation hook or create a temporary field (within PHP, do NOT use client sided tech for this job!) with the sum of all the necessary fields and validate against it.

$validator = Validator::make([
    'field1' => 50,
    'field2' => 25,
    'field3' => 22,
], [
    'field1' => 'required|numeric',
    'field2' => 'required|numeric',
    'field3' => 'required|numeric',
]);

$validator->after(function ($validator) {
    if ($validator->getData()['field1']   $validator->getData()['field2']   $validator->getData()['field3'] !== 100) {
        $validator->errors()->add('field1', 'Make sure the sum of all fields equals 100.');
    }
});

CodePudding user response:

You can extend the validator with a new rule by adding this in a service provider:

$validator->extend("sumsTo", function ($attribute, $value, $parameters) {
   $expected = floatval(array_shift($parameters));
   $otherParameters = request()->only($parameters);
   return floatval(array_sum(array_merge(array_values($otherParameters), [ $value ]))) === $expected;
});

Then you'd use this as:

$request->validate([
      'field1' => 'sumsTo:100,field2,field3',
      'field2' => 'sumsTo:100,field1,field3'
      'field3' => 'sumsTo:100,field1,field2'
]);

This will flag all 3 fields as failed as well.

  • Related