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"; }
TRANSLATE with x English TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back 标签:laravel,function,封装,验证,required,location,return,document,public From: https://www.cnblogs.com/bing2017/p/16869435.html