1

Currently I have working foreach array where it collects all tasks and it contains weight for each task.

Here's my working code

foreach ($arr4 as $row4) {
    $taskCode = strtoupper(str_random(12));
    $insert_data5[] = array(
        'projCode'  =>  $projCode,
        'taskCode'  => $taskCode,
        'taskWeight'  =>  $row4['weight'],
        'plan_days' =>  $row4['planned_days'],
        'actual_days'  =>  $row4['actual_days'],
        'deleted'  =>  0,
        'by_id'  => auth()->user()->id,
        'updated_by'    =>  auth()->user()->name,
        'created_at'    =>  now(),
        'updated_at'    => now(),
        );

}

dd($insert_data5);

OUTPUT

enter image description here

What I'm trying to do is to validate if the sum up of taskWeight of 5 Tasks doesn't reached 100% this will show an error message.

As of now my idea is to use validator but I have no idea how can I calculate the array fields of taskWeight

  $validator = Validator::make(
                $insert_data5,
                [
                   ......
                ]
            );


   if($validator->fails()){
                return redirect()
                ->back()
                ->with(['errors'=>$validator->errors()->all()])
                ->with('modal',$modal);
            }
4
  • What do you want here? did you mean to ask how to limit total sum of taskWeight to be less than 100? and what does that 5 Tasks mean? did you mean to say you want sum of 5 tasks or there are total 5 tasks? Commented Jan 9, 2020 at 8:33
  • I mean, if I sum up all the tasks using taskWeight this should not exceeds 100%. I just want to limit the total sum up into 100% and if the total sum up of taskWeight is <100 there's a validation will appear that says it should be exact 100% Commented Jan 9, 2020 at 8:35
  • why do you want to do it on the server side? Commented Jan 9, 2020 at 8:37
  • because the $insert_data5 contains the data of excel file Commented Jan 9, 2020 at 8:37

1 Answer 1

1

Fixed my problem

I declare $ttlTaskWeight = 0; outside of foreach

Then as suggested do the sum up inside of the foreach

like this

$ttlTaskWeight += $row4['weight'];

and I did this to validate if it exceeds 100% or not

    if($ttlTaskWeight != 100){
                return redirect()
                ->back()
                ->with(['errors'=> [0=> 'Total Task Weight must be exact 100%']])
                ->with('modal',$modal);
            }

and the output is this

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

99 !=100 true and 101 !=100 also true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.