-
I'm trying to add some custom rules, those rules need to be available as string and not as classes (This is an important requirement) I could achieve this using: foreach ([RequiredIfContains::class, RequiredUnlessContains::class] as $rule) {
/** @var Validator $validator */
$validator = $this->app['validator'];
$validator->extend(class_basename($rule), $rule.'@passes');
} And a rule looks like <?php
namespace App\Rules;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Support\Arr;
use Illuminate\Validation\Validator;
class RequiredIfContains extends Rule implements DataAwareRule, ValidatorAwareRule
{
/**
* Set the data under validation.
*
* @param array $data
* @return $this
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$parameters = $this->parameters;
$this->validator->requireParameterCount(2, $parameters, 'required_if_contains');
if (! Arr::has($this->data, $parameters[0])) {
return true;
}
[$values, $other] = $this->validator->parseDependentRuleParameters($parameters);
if (is_array($other)) {
foreach ($values as $val) {
if (in_array($val, $other, is_bool($val) || is_null($val))) {
return $this->validator->validateRequired($attribute, $value);
}
}
}
return true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return trans('validation.required_if');
}
public function setValidator($validator)
{
$this->validator = $validator;
}
} They work perfectly fine as class rules, but as rule extensions, the validator and data are never set on the rule, so it doesn't work Missing feature on the extension part? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Seems the last parameter of the function is the validator, so I was able to do this instead public function validate($attribute, $value, $parameters, Validator $validator)
{
$this->parameters = $parameters;
if ($this instanceof ValidatorAwareRule) {
$this->setValidator($validator);
}
if ($this instanceof DataAwareRule) {
$this->setData($validator->getData());
}
$res = $this->passes($attribute, $value);
if (!$res) {
$validator->fallbackMessages[Str::snake(class_basename($this))] = $this->message();
}
return $res;
} And $validator->extend(class_basename($rule), $rule); |
Beta Was this translation helpful? Give feedback.
-
I have solved the exact problem in the following package: https://github.com/henzeb/ruler-laravel |
Beta Was this translation helpful? Give feedback.
Seems the last parameter of the function is the validator, so I was able to do this instead
And