1,在命令行 新建 App\Http\Requests\UserRequest.php 用户表单检验文件
php artisan make:request UserRequest
2,编辑上一步生成的 UserRequest.php 如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class UserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ "username" => 'required|unique:users', "password" => "required" ]; } public function messages() { return [ "username.required" => "用户名不能为空", "username.unique" =>"用户名不能重复", "password.required" =>"密码不能为空" ]; } }
3,App\Http\Controllers\Admin\UserController.php 的 indexSave() 方法里的第一个参数 Request 改成 UserRequest 【即 接收新增用户的数据时引用了 UserRequest.php上的校验方法】如下图示
4,\resources\views\Admin\User\add.blade.php 如图所示出增加红框所示代码【引用提示信息模块】
@include('Admin.Layout.msg')
测试 验证的效果,浏览器访问 http://laravel.pensive.top/admin/user/add 然后新增一个已存在的用户名admin 后提交会 有提示 用户名不能重复 如下图示
END