现在到了后台验证的时候了;
laravel 可以直接在控制器中直接写验证逻辑;
不过我建议单独创建验证类;
以控制器名为目录;
以方法名为文件名;
这里为 store 方法创建一个验证类;
[cc]php artisan make:request Validation/Store[/cc]
执行命令会生成 app/Http/Requests/Validation/Store.php 文件;
[cc] {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}[/cc]
默认生成的验证类中只有 authorize
和 rules
方法;
authorize()
主要用于验证权限;
如上面代码所示默认直接返回 fase
意味着所有的请求都不能通过验证;
假如说只允许 user_id
为 1 的用户执行 store
方法;
我们可以这样改写 验证类的 authorize()
;
[cc]public function authorize()
{
return Auth::id() === 1 ? true : false;
}[/cc]
还有很多时候我们并不需要验证身份;
那直接返回 true
即可;
[cc]public function authorize()
{
return true;
}[/cc]
另外就是 rules
方法;
根据前端页面增加以下验证;
[cc]public function rules()
{
return [
‘tag’ => ‘required’,
‘name’ => ‘required|string|max:255′,
’email’ => ‘required|string|email|max:255|unique:users’,
‘password’ => ‘required|string|min:6|confirmed’,
];
}[/cc]
这些规则都可以在文档中找到表单验证 ;
要使用这个验证器也很简单;
只需要在 store
方法的类型约束中使用 Store
即可;
[cc]use App\Http\Requests\Validation\Store;
public function store(Store $request)
{
dump($request->all());
}[/cc]
评论(0)