简体   繁体   中英

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]);

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM