兵兵有你

人品好,气质差.丢了工作就回家...

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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";
    }

  

 

 

 

 

 

 

 

 

posted on 2022-11-08 13:47  greatbing  阅读(47)  评论(0编辑  收藏  举报