Rajesh Kumar
Rajesh Kumar

Reputation: 247

Laravel custom validation - get parameters

I want to get the parameter passed in the validation rule.

For certain validation rules that I have created, I'm able to get the parameter from the validation rule, but for few rules it's not getting the parameters.

In model I'm using the following code:

public static $rules_sponsor_event_check = array(
    'sponsor_id' => 'required',
    'event_id' => 'required|event_sponsor:sponsor_id'
);

In ValidatorServiceProvider I'm using the following code:

    Validator::extend('event_sponsor', function ($attribute, $value, $parameters) {
        $sponsor_id = Input::get($parameters[0]);
        $event_sponsor = EventSponsor::whereIdAndEventId($sponsor_id, $value)->count();

        if ($event_sponsor == 0) {
            return false;
        } else {
            return true;
        }
    });

But here I'm not able to get the sponsor id using the following:

$sponsor_id = Input::get($parameters[0]);

Upvotes: 11

Views: 21357

Answers (2)

lukasgeiter
lukasgeiter

Reputation: 152860

As a 4th the whole validator is passed to the closure you define with extends. You can use that to get the all data which is validated:

Validator::extend('event_sponsor', function ($attribute, $value, $parameters, $validator) {
    $sponsor_id = array_get($validator->getData(), $parameters[0], null);
    // ...
});

By the way I'm using array_get here to avoid any errors if the passed input name doesn't exist.

Upvotes: 20

Ezequiel Moreno
Ezequiel Moreno

Reputation: 2348

http://laravel.com/docs/5.0/validation#custom-validation-rules

The custom validator Closure receives three arguments: the name of the $attribute being validated, the $value of the attribute, and an array of $parameters passed to the rule.

Why Input::get( $parameters ); then? you should check $parameters contents.

Edit. Ok I figured out what are you trying to do. You are not going to read anything from input if the value you are trying to get is not being submitted. Take a look to

dd(Input::all());

You then will find that

sponsor_id=Input::get($parameters[0]);

is working in places where sponsor_id was submited.

Upvotes: 0

Related Questions