官方文档,shttps://learnku.com/docs/laravel/8.5/validation/10378
上文说道。Laravel 自定义验证器
开始这篇之前记得删除打印日志
想必各位懂得都懂。
验证的规则写到这里 代码会很冗余的
官方给了提取的命令
但是仅限于app那种模式下。
模块化的命令稍微改动
在Admin模块下新建 TestRequest文件 头铁的老铁当然自己创建也行
php artisan module:make-request TestRequest Admin
会在这个目录生成一个request文件
<?php
namespace Modules\Admin\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TestRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
}
完善这个类
<?php
namespace Modules\Admin\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
class TestRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|max:2|is_positive_integer',
'body' => 'required',
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
public function messages()
{
return [
'title.required' => "请输入标题",
'title.max' => "标题最大长度不能超过2个字符",
'title.is_positive_integer' => "请设置为正整数的标题",
];
}
protected function failedValidation(Validator $validator)
{
dd($validator->errors()->messages());
}
}
之前的test的代码
public function test(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|max:2|is_positive_integer',
'body' => 'required',
], [
'title.required' => "请输入标题",
'title.max' => "标题最大长度不能超过2个字符",
'title.is_positive_integer' => "请设置为正整数的标题",
]);
if ($validator->fails()) {
return $validator->errors()->messages()['title'][0];
}
return "hello world";
// 博客文章验证通过...
}
参数2代表验证器
之后的test
<?php
/**
* @Description
* @Date 2021-12-19 21:44
*/
namespace Modules\Admin\Http\Controllers\v1;
//集成核心Controller
use Illuminate\Routing\Controller;
use Modules\Admin\Http\Requests\TestRequest;
class IndexController extends Controller
{
public function test(TestRequest $request)
{
return "Hello world";
// 博客文章验证通过...
}
}
控制器层保持干净与整洁