当我们使用 php artisan make:request 创建验证对象的时候
里面用 rules()方法,但是默认只定义了一组规则.
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required'
];
}
问题: 如何根据不同的方法名,创建多组验证规则?比如"查看","编辑",'插入' 需要有3组不同的规则.
方法 : 首先需要知道当前是什么操作,才能知道该用哪组规则,通过 request对象的$this->segment()方法,来获取 url的信息.比如 http://localhost:8000/submit ,用 $this->segment(1) 值就是 submit.
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$type = $this->segment(1);
if ($type == 'submit') {
return [
'name' => 'required'
];
}elseif($type == 'update'){
return [
'id' => 'required'
];
}
}
如果还有其他更好的方法,还请留言,谢谢!