执行 php artisan make:request StoreBlogPost后,在生成的类中,生成authorize方法,默认返回值为false,若不需要判断权限认证,把返回值
修改成true才可,否则报错信息如下
Symfony \ Component \ HttpKernel \ Exception \ AccessDeniedHttpException
This action is unauthorized.
生成的类中默认有authorize和rules方法,可手动添加messages和attributes方法完成以上功能.
public function authorize()
{
return false;
}
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
];
}
public function messages()
{
return [
'required'=>':attribute为必填项',
'max'=>':attribute长度超过最大限制,最大255个字节',
'unique'=>':attribute必须是唯一的'
];
}
public function attributes()
{
return [
'title'=>'题目',
'author.name'=>'用户名称',
'author.description'=>'用户描述'
];
}
在控制器使用中,把依赖注入Request换成自己生成的类名,即可自动完成验证.如下:
public function create(StoreBlogPost $request)
{
}