Accessing the $validator property inside the $callback function of ClosureValidationRule #49006
-
My problemHello everyone. I'm creating a custom validation rule using Closure, and inside that rule I need to access other fields in the data array I'm validating. A lot of articles suggest accessing fields from the request, but that won't work for me since I'm validating an array loaded from a CSV file inside a loop. IdeaI looked at the ClosureValidationRule source code, and it would be really helpful if the $validator property could be passed as a 4th argument to the $callback function. That way I could access the data array inside my custom rule. https://github.com/laravel/framework/blob/10.x/src/Illuminate/Validation/ClosureValidationRule.php public function passes($attribute, $value)
{
$this->failed = false;
$this->callback->__invoke($attribute, $value, function ($attribute, $message = null) {
$this->failed = true;
return $this->pendingPotentiallyTranslatedString($attribute, $message);
- });
+ }, $this->validator);
return ! $this->failed;
} Usagehttps://laravel.com/docs/10.x/validation#using-closures use Closure;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\LazyCollection;
+ use Illuminate\Validation\Validator as ValidationValidator;
$rules = [
'price' => [
- function (string $attribute, mixed $value, Closure $fail) {
+ function (string $attribute, mixed $value, Closure $fail, ValidationValidator $validator) {
- if ($value === 'foo') {
+ if (!price_logic($value, $validator->attributes()['payment_country'] ?? null)) {
$fail("The {$attribute} is invalid.");
}
},
],
];
/** @var LazyCollection $csv_rows */
$csv_rows = next_row_from_csv();
foreach ($csv_rows as $row) {
if (Validator::make($row, $rules)->failed()) {
break;
}
} That's my idea. I'm a bit stuck and could use some help with this. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
⇧ - $validator->attributes()['payment_country'] ?? null
+ $validator->getValue('payment_country') This pull request may be relevant: #49007 |
Beta Was this translation helpful? Give feedback.
-
You could use the use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
class ValidPrice implements DataAwareRule, ValidationRule
{
protected $data = [];
public function setData(array $data): static
{
$this->data = $data;
return $this;
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!price_logic($value, $this->data['payment_country'] ?? null)) {
$fail("The {$attribute} is invalid.");
}
}
} More info here under the |
Beta Was this translation helpful? Give feedback.
-
Merged #49015 into 10.x. |
Beta Was this translation helpful? Give feedback.
Merged #49015 into 10.x.