From 7330b9251c0637e6a50b5d31da7ae06ef1ca53a0 Mon Sep 17 00:00:00 2001 From: Owen Andrews Date: Tue, 25 Jun 2024 06:15:22 +1000 Subject: [PATCH] [11.x] Fix validation attributes when translations are empty or missing (#51890) * Check custom attributes array is set * Add test for when translated validation attributes are missing * Skip translated attributes if not set or empty * StyleCI fixes --- .../Validation/Concerns/FormatsMessages.php | 8 +++++--- tests/Validation/ValidationValidatorTest.php | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/Illuminate/Validation/Concerns/FormatsMessages.php b/src/Illuminate/Validation/Concerns/FormatsMessages.php index c03e2636a51e..4fc6c1fa4807 100644 --- a/src/Illuminate/Validation/Concerns/FormatsMessages.php +++ b/src/Illuminate/Validation/Concerns/FormatsMessages.php @@ -305,9 +305,11 @@ public function getDisplayableAttribute($attribute) */ protected function getAttributeFromTranslations($name) { - return $this->getAttributeFromLocalArray( - $name, Arr::dot((array) $this->translator->get('validation.attributes')) - ); + if (! is_array($attributes = $this->translator->get('validation.attributes'))) { + return null; + } + + return $this->getAttributeFromLocalArray($name, Arr::dot($attributes)); } /** diff --git a/tests/Validation/ValidationValidatorTest.php b/tests/Validation/ValidationValidatorTest.php index af2c22a60c51..2a207bb8813c 100755 --- a/tests/Validation/ValidationValidatorTest.php +++ b/tests/Validation/ValidationValidatorTest.php @@ -592,6 +592,20 @@ public function testTranslatedAttributeNamesAreReplacedInArraysFromNestedRules() $this->assertSame('User ID is required!', $v->messages()->first('users.0.id')); } + public function testTranslatedAttributesCanBeMissing() + { + $trans = $this->getIlluminateArrayTranslator(); + $trans->addLines(['validation.gt.numeric' => ':attribute must be greater than :value.'], 'en'); + $trans->addLines(['validation.attributes' => []], 'en'); + $v = new Validator($trans, ['total' => 0], ['total' => 'gt:0']); + $this->assertSame('total must be greater than 0.', $v->messages()->first('total')); + + $trans = $this->getIlluminateArrayTranslator(); + $trans->addLines(['validation.gt.numeric' => ':attribute must be greater than :value.'], 'en'); + $v = new Validator($trans, ['total' => 0], ['total' => 'gt:0']); + $this->assertSame('total must be greater than 0.', $v->messages()->first('total')); + } + public function testInputIsReplaced() { $trans = $this->getIlluminateArrayTranslator();