Laravel FormRequest 검증을 수정하고 시나리오 검증을 구현하는 방법을 가르쳐주세요.

藏色散人
풀어 주다: 2020-09-10 11:11:25
앞으로
3400명이 탐색했습니다.

튜토리얼 칼럼에서 검증할 Laravel FormRequest에 대한 검증입니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

Laravel에서는 생성 및 편집된 많은 인터페이스에 데이터 확인이 필요합니다. 데이터 확인에는 일반적으로 두 가지 방법이 있습니다.

Laravel FormRequest 검증을 수정하고 시나리오 검증을 구현하는 방법을 가르쳐주세요.

컨트롤러에서 직접 Request의 확인 방법을 사용하세요

  • 커스텀

    FormRequest
  • 클래스를 사용하세요. ,
  • HttpRequest

    첫 번째 방법을 사용하면 지저분하고 우아하지 않습니다하지만 두 번째 방법을 사용하면 각 요청에 대해 FormRequest를 정의합니다

    예:

    ArticleStoreRequest

    ArticleUpdateRequest

    그러나 유효성 검사 규칙은 기본적으로 동일하다는 것을 알 수 있습니다. 물론 컨트롤러 메서드에는 요청을 하나만 삽입할 수 있지만 모델에 대해 사용자와 같은 업데이트 종류가 많은 경우 모듈에서는 비밀번호 변경/닉네임 수정/아바타 수정/주소 수정/수정을 할 수 있습니다. . . 어떻게 처리해야 할까요그래서 지난 며칠간 이런 상황에 대응하여 Laravel의 요청 메커니즘이 개선되었고 시나리오 검증이 추가되었습니다

    1단계: 먼저

    AbstractRequest

    • <?php
      
      namespace App\Http\Requests;
      
      use Illuminate\Foundation\Http\FormRequest;
      use Illuminate\Support\Str;
      
      /**
       * 使用方法:
       * Class AbstractRequest
       * @package App\Http\Requests
       */
      class AbstractRequest extends FormRequest
      {
          public $scenes = [];
          public $currentScene;               //当前场景
          public $autoValidate = false;       //是否注入之后自动验证
          public $extendRules;
      
          public function authorize()
          {
              return true;
          }
      
          /**
           * 设置场景
           * @param $scene
           * @return $this
           */
          public function scene($scene)
          {
              $this->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);
              }
          }
      
      }
      로그인 후 복사
      의 기본 클래스를 만듭니다. 두 번째 단계: 사용자 요청의 경우
    • UserRequest
    상속된
      AbstractRequest
    • <?php
      
      namespace App\Http\Requests;
      
      class UserRequest extends AbstractRequest
      {
        public $scenes = [
            &#39;nickname&#39; => '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处理才能判断是否相同
                ]
            ];
        }
      }
      로그인 후 복사
      Controller 메서드
    • UserController
    • <?php
      
      namespace App\Http\Controllers;
      
      use App\Http\Requests\UserRequest;
      
      class UserController
      {
      
          public function register(UserRequest $request)
          {
              $request->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가 주입될 때 컨트롤러에 도달할 때 자동 확인을 수행하지 마십시오. 물론 자동 확인이 필요한 경우
    • $autoValidate = true
    로 설정하면 됩니다.

    위 내용은 참고용입니다. 가벼운 스프레이를 바랍니다. 동시에 여러 장면 생성 및 업데이트 요구 사항을 동시에 충족하기 위해 모델에서 자주 설정할 수 있는 ORM의 장면 확인 규칙도 수정했습니다

위 내용은 Laravel FormRequest 검증을 수정하고 시나리오 검증을 구현하는 방법을 가르쳐주세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:learnku.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!