美文网首页
laravel api项目处理Request验证

laravel api项目处理Request验证

作者: charmingcheng | 来源:发表于2021-05-14 16:38 被阅读0次

    新建一个Request抽象类,其他的Request都继承于它

    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    use Illuminate\Contracts\Validation\Validator;
    use Illuminate\Http\Exceptions\HttpResponseException;
    
    abstract class Request extends FormRequest
    {
        protected function failedValidation(Validator $validator)
        {
            $errormsg = $validator->errors()->messages();
            foreach ($errormsg  as $item) {
                $msg = current($item);
                break;
            };
    
            throw (new HttpResponseException(response()->json([
                'code' => 1,
                'message' => $msg,
            ], 422)));
        }
    }
    

    使用示例

    namespace App\Http\Requests; 
    
    class UserRequest extends Request
    {  
        public function rules()
        {
            return [
              "username" => "required|string",
              "password" => "required|string|min:6"
            ];
        }
        
        public function messages()
        {
          return [
            "username.requried" => "请填写用户名",
            "username.string" => "用户名必须为字符串",
            "password.required" => "请填写密码",
            "password.string" => "密码必须为字符串",
            "password.min" => "密码不少于6位"
          ];
        }
    }
    

    相关文章

      网友评论

          本文标题:laravel api项目处理Request验证

          本文链接:https://www.haomeiwen.com/subject/nklhnhtx.html