skip to Main Content
 'boulders_per' => 'numeric',
            'fine_soil_per' => 'numeric',
            Rule::sometimes(function () {
                $sum = $this->input('boulders_per', 0) + $this->input('fine_soil_per', 0);
                return $sum !== 100;
            }),

used requiredif bt these fileds are not always required to be filled and using sometimes its shows error
"message": "Method IlluminateValidationRule::sometimes does not exist.",

2

Answers


  1. You might try to implement this on top of your controller(or wherever you use that function):

    use IlluminateSupportFacadesValidator;

    Login or Signup to reply.
  2. Method : 1

    You must use Custom Validation Rules for single attribute validations.

    There is a provision in After Validation Hooks where such kind of complex validation can be written

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->get('your_field_1') + $this->get('your_field_2') + $this->get('your_field_3') + $this->get('your_field_4') != 100) {
                $validator->errors()->add(null, 'The sum of field1, field2 and field3 and field4 must be 100');
            }
        });
    }
    

    Method : 2

    Your can convert the value from an array to a collection and use the sum collect method

    public function passes($attribute, $value) {
        $values = collect($value);    
        return $values->sum('percentage') <= 100;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search