Epsilon47
Epsilon47

Reputation: 838

Retrieve parameters from custom validation object

I have basic custom validation rule. In

public function passes($attribute, $value)
{
    foreach ($parameters as $key)
    {
        if ( ! empty(Input::get($key)) )
        {
            return false;
        }
    }

    return true;
}

I have my rule defined. I, although need to retrieve parameters from the rule but the passes method does not provide it as an argument.

If I would use the style Validator:extends... that provides 4 arguments: $attribute, $value, $parameters, $validator. Then I could use the parameters easily, unfortunatelly I have to use this way.

EDIT:

To clear the question. I want to retrieve the parameters of the rule, like so in other way of coding it: 'not_empty:user_id'. The array of values behind the colon.

Upvotes: 0

Views: 139

Answers (2)

Jeff
Jeff

Reputation: 25221

Edit:---

The custom rule object is simply an object. If you want to pass it any more parameters you can in it's constructor:

$request->validate([
    'name' => ['required', new MyCustomRule('param', true, $foo)],
]);

Then save those and use them in your passes function.

public function __construct($myCustomParam){
    $this->myCustomParam = $myCustomParam;
}

Then in your passes function use:

$this->myCustomParam

Upvotes: 1

Alex
Alex

Reputation: 1638

I believe the only way is to retrieve it from the request when using rule objects.

For example:

public function passes($attribute, $value)
{
    foreach ($parameters as $key) {
        // Or using \Request::input($key) if you want to use the facade
        if (!empty(request()->input($key)) { 
            return false;
        }
    }

    return true;
 }

Upvotes: 1

Related Questions