1.先编写基类 baseRequest.php
<?php
namespace App\validate;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class BaseRequest extends FormRequest
{
public function rules(){
$rule_action = "getRulesBy".ucfirst($this->route()->getActionMethod());
if(method_exists($this,$rule_action)){
return $this->$rule_action();
}
}
public function getDefaultRules(): array
{
return [];
}
public function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
"code"=> 0,
"msg" => $validator->errors()->first()
]));
//parent::failedValidation($validator); // TODO: Change the autogenerated stub
}
}
2.业务验证类 PostRequest .php
<?php
namespace App\validate;
class PostRequest extends BaseRequest
{
public function getRulesByBing2(){
return [
'title' => "required|min:4",
'body' => 'required'
];
}
public function messages()
{
return [
'title.required' => '标题一定要有',
'body.required' => 'BODY一定要有',
'title.min'=> '不能少于4'
];
}
}
3.控制器里的写法
public function bing2(PostRequest $request){
echo "success";
}
浙公网安备 33010602011771号