Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
like image 276
Rajesh Kumar Avatar asked May 18 '15 06:05

Rajesh Kumar


1 Answers

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.

like image 156
lukasgeiter Avatar answered Oct 24 '22 12:10

lukasgeiter