From dda17ec9d816bbf1da4512b5f8a6775b5681caee Mon Sep 17 00:00:00 2001 From: Mohammad Mortazavi <39920372+hans-thomas@users.noreply.github.com> Date: Sun, 27 Aug 2023 19:19:25 +0330 Subject: [PATCH] [10.x] Fix validation of attributes that depend on previous excluded attribute (#48122) * fix validation of attributes that depend on others with exclude rule applied * fixed style * Validator's passes methods fixed; * tests added for passes method; * Apply fixes from StyleCI; * rename the test; * formatting --------- Co-authored-by: Philip Iezzi Co-authored-by: Taylor Otwell --- src/Illuminate/Validation/Validator.php | 8 +++-- tests/Validation/ValidationValidatorTest.php | 33 ++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Validation/Validator.php b/src/Illuminate/Validation/Validator.php index 12f2016e0c9d..4a7b5f99fe2d 100755 --- a/src/Illuminate/Validation/Validator.php +++ b/src/Illuminate/Validation/Validator.php @@ -437,8 +437,6 @@ public function passes() $this->validateAttribute($attribute, $rule); if ($this->shouldBeExcluded($attribute)) { - $this->removeAttribute($attribute); - break; } @@ -448,6 +446,12 @@ public function passes() } } + foreach ($this->rules as $attribute => $rules) { + if ($this->shouldBeExcluded($attribute)) { + $this->removeAttribute($attribute); + } + } + // Here we will spin through all of the "after" hooks on this validator and // fire them off. This gives the callbacks a chance to perform all kinds // of other validation that needs to get wrapped up in this operation. diff --git a/tests/Validation/ValidationValidatorTest.php b/tests/Validation/ValidationValidatorTest.php index 2b5f735065c3..e7178b674c30 100755 --- a/tests/Validation/ValidationValidatorTest.php +++ b/tests/Validation/ValidationValidatorTest.php @@ -8257,6 +8257,39 @@ public function testExclude($rules, $data, $expectedValidatedData) $this->assertSame($expectedValidatedData, $validator->validated()); } + public function testExcludeBeforeADependentRule() + { + $validator = new Validator( + $this->getIlluminateArrayTranslator(), + [ + 'profile_id' => null, + 'type' => 'denied', + ], + [ + 'type' => ['required', 'string', 'exclude'], + 'profile_id' => ['nullable', 'required_if:type,profile', 'integer'], + ], + ); + + $this->assertTrue($validator->passes()); + $this->assertSame(['profile_id' => null], $validator->validated()); + + $validator = new Validator( + $this->getIlluminateArrayTranslator(), + [ + 'profile_id' => null, + 'type' => 'profile', + ], + [ + 'type' => ['required', 'string', 'exclude'], + 'profile_id' => ['nullable', 'required_if:type,profile', 'integer'], + ], + ); + + $this->assertFalse($validator->passes()); + $this->assertSame(['profile_id' => ['validation.required_if']], $validator->getMessageBag()->getMessages()); + } + public function testExcludingArrays() { $validator = new Validator(