Laravel 自定义验证 - 获取参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30296615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel custom validation - get parameters
提问by Rajesh Kumar
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:
在 ValidatorServiceProvider 中,我使用以下代码:
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:
但是在这里我无法使用以下内容获取赞助商 ID:
$sponsor_id = Input::get($parameters[0]);
回答by lukasgeiter
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:
作为第四个,整个验证器被传递给你定义的闭包extends
。您可以使用它来获取所有经过验证的数据:
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.
顺便说array_get
一下,如果传递的输入名称不存在,我在这里使用以避免任何错误。
回答by Ezequiel Moreno
http://laravel.com/docs/5.0/validation#custom-validation-rules
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.
自定义验证器闭包接收三个参数:被验证的 $attribute 的名称、属性的 $value 以及传递给规则的 $parameters 数组。
Why Input::get( $parameters );
then? you should check $parameters contents.
那为什么Input::get( $parameters );
?您应该检查 $parameters 内容。
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.
在提交sponsor_id的地方工作。