首頁  >  文章  >  php框架  >  教你修改Laravel FormRequest驗證,實作場景驗證

教你修改Laravel FormRequest驗證,實作場景驗證

藏色散人
藏色散人轉載
2020-09-10 11:11:253284瀏覽

在Laravel 中,許多建立和編輯的的介面都是需要做資料驗證的,對於資料驗證一般有2種方方式

教你修改Laravel FormRequest驗證,實作場景驗證在控制器裡直接使用Request的validate方法

    使用自訂
  • FormRequest

    類,該類別整合自

    Http\Request
  • 如果使用第一種方法,會比較亂,看起來不夠優雅但是如果使用第二種方式,那麼針對每一種請求都要定義一個FormRequest例如:

    ArticleStoreRequest

    ArticleUpdateRequest

    但是你會發現基本上驗證規則是一樣的,當然你可以在控制器方法裡只注入一個Request,但如果針對於一個Model 有多個Update的那種,例如使用者模組,修改密碼/修改暱稱/修改頭像/修改位址/修改。 。 。怎麼處理呢所以這幾天針對這種情況,改進了下Laravel的Request機制,加了一個場景驗證

    第一步:先建立一個

    AbstractRequest

    的基底類別

    currentScene = $scene;
            return $this;
        }
    
        /**
         * 使用扩展rule
         * @param string $name
         * @return AbstractRequest
         */
        public function with($name = '')
        {
            if (is_array($name)) {
                $this->extendRules = array_merge($this->extendRules[], array_map(function ($v) {
                    return Str::camel($v);
                }, $name));
            } else if (is_string($name)) {
                $this->extendRules[] = Str::camel($name);
            }
    
            return $this;
        }
    
        /**
         * 覆盖自动验证方法
         */
        public function validateResolved()
        {
            if ($this->autoValidate) {
                $this->handleValidate();
            }
        }
    
        /**
         * 验证方法
         * @param string $scene
         * @throws \Illuminate\Auth\Access\AuthorizationException
         * @throws \Illuminate\Validation\ValidationException
         */
        public function validate($scene = '')
        {
            if ($scene) {
                $this->currentScene = $scene;
            }
            $this->handleValidate();
        }
    
        /**
         * 根据场景获取规则
         * @return array|mixed
         */
        public function getRules()
        {
            $rules = $this->container->call([$this, 'rules']);
            $newRules = [];
            if ($this->extendRules) {
                $extendRules = array_reverse($this->extendRules);
                foreach ($extendRules as $extendRule) {
                    if (method_exists($this, "{$extendRule}Rules")) {   //合并场景规则
                        $rules = array_merge($rules, $this->container->call(
                            [$this, "{$extendRule}Rules"]
                        ));
                    }
                }
            }
            if ($this->currentScene && isset($this->scenes[$this->currentScene])) {
                $sceneFields = is_array($this->scenes[$this->currentScene])
                    ? $this->scenes[$this->currentScene] : explode(',', $this->scenes[$this->currentScene]);
                foreach ($sceneFields as $field) {
                    if (array_key_exists($field, $rules)) {
                        $newRules[$field] = $rules[$field];
                    }
                }
                return $newRules;
            }
            return $rules;
        }
    
        /**
         * 覆盖设置 自定义验证器
         * @param $factory
         * @return mixed
         */
        public function validator($factory)
        {
            return $factory->make(
                $this->validationData(), $this->getRules(),
                $this->messages(), $this->attributes()
            );
        }
    
        /**
         * 最终验证方法
         * @throws \Illuminate\Auth\Access\AuthorizationException
         * @throws \Illuminate\Validation\ValidationException
         */
        protected function handleValidate()
        {
            if (!$this->passesAuthorization()) {
                $this->failedAuthorization();
            }
            $instance = $this->getValidatorInstance();
            if ($instance->fails()) {
                $this->failedValidation($instance);
            }
        }
    
    }
    • 第二步:針對使用者Request,我們只需要定義一個UserRequest繼承
    • AbstractRequest
    •  'nickname',
            'avatar' => 'avatar',
            'password' => 'password',
            'address' => 'province_id,city_id'
        ];
      
        public function rules()
        {
            return [        //全部的验证规则
                'mobile' => [],
                'nickname' => [],
                'password' => [
                    'required', 'min:6', 'max:16'
                ],
                'avatar' => [],
                'province_id' => [],
                'city_id' => [],
                //...
            ];
        }
      
        public function passwordRules()
        {
            return [
                'password' => [
                    'required', 'min:6', 'max:16', 'different:$old_password'      //修改新密码不和旧密码相同,此处只是举例子,因为密码需要Hash处理才能判断是否相同
                ]
            ];
        }
      }
      控制器方法UserController
    validate();   //默认不设置场景 全部验证
            //...
        }
    
        public function updateAddress($id, UserRequest $request)
        {
            $request->scene('address')->validate();
            //...
        }
    
        public function updateAvatar($id, UserRequest $request)
        {
            $request->validate('avatar');
            //...
        }
    
        public function updatePassword($id, UserRequest $request)
        {
            //设置password场景,只验证password字段,并且使用新的password规则替换原来的password规则
            $request->scene('password')
                ->with('password')
                ->validate();
            //...
        }
    }
    • 該方法沒有修改Laravel的核心驗證邏輯,只讓在FormRequest在註入到Controller的時候不要做自動驗證,當然,如果需要自動驗證,那麼設定$autoValidate = true即可。
    以上內容僅供參考。望輕噴。

    同時還有我也修改了ORM的場景驗證規則,可以在model裡設定經常,同時滿足多場景建立和更新

以上是教你修改Laravel FormRequest驗證,實作場景驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除