Common Laravel validation - get parameters

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

For some validation rules that I created, I can get the parameter from the validation rule, but for several rules it does not receive the parameters.

In the model, I use the following code:

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

In ValidatorServiceProvider, I use 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 can not get the sponsor ID using the following:

 $sponsor_id = Input::get($parameters[0]); 
+6
source share
2 answers

As the fourth, the entire validator is passed to the closure that you define using extends . You can use this to get all the confirmed data:

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

By the way, I use array_get here to avoid errors if the name of the input passed does not exist.

+10
source

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

The user closure of the validator receives three arguments: the name $ attribute, the value of $ attribute, and the array of $ parameters passed to the rule.

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

Change Ok, I understand what you are trying to do. You will not read any of the input if the value you are trying to get is not sent. Take a look at

 dd(Input::all()); 

Then you will find that

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

works in places where sponsor_id was sent.

0
source

Source: https://habr.com/ru/post/987398/


All Articles