search
HomePHP FrameworkLaravelTeach you how to modify Laravel FormRequest verification and implement scenario verification

The following tutorial column will introduce to you how to modify Laravel FormRequest verification and implement scenario verification. I hope it will be helpful to friends in need!

In Laravel, many interfaces created and edited require data verification. There are generally two methods for data verification

Teach you how to modify Laravel FormRequest verification and implement scenario verification

Use the validate method of Request directly in the controller

  • Use the custom

    FormRequest
  • class, which is integrated from
  • Http\Request

    If you use the first method, it will be messy and not elegant enoughBut if you use the second method, then a FormRequest must be defined for each request

    For example:

    ArticleStoreRequest

    and

    ArticleUpdateRequest

    But you will find that the validation rules are basically the same. Of course, you can only inject one in the controller method Request, but if there are multiple Updates for a Model, such as user module, change password/modify nickname/modify avatar/modify address/modify. . . How to deal with itSo in response to this situation in the past few days, Laravel's Request mechanism has been improved and a scenario verification has been added

    The first step: Create a

    Base class of 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);
              }
          }
      
      }
      Step 2: For user Request, we only need to define a
    • UserRequest
    Inheritance
      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 method
    • 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();
              //...
          }
      }
      This method does not modify the core validation logic of Laravel, only allows the injection in the FormRequest Do not do automatic verification when you get to the Controller. Of course, if you need automatic verification, just set
    • $autoValidate = true
    .

    The above content is for reference only. Hope light spray. At the same time, I also modified the scene verification rules of ORM, which can be set frequently in the model to satisfy the creation and update of multiple scenes at the same time

The above is the detailed content of Teach you how to modify Laravel FormRequest verification and implement scenario verification. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Explain Laravel Events and Listeners functionality.Explain Laravel Events and Listeners functionality.Jul 23, 2025 am 03:22 AM

Laravel's Events and Listeners are used to decouple application modules. Events indicate "what happened", such as user registration or order payment; listeners define "what to do", such as sending emails or logging. 1. The event class is stored in app/Events, carrying relevant information; 2. The listener is stored in app/Listeners, responding to events through handle methods; 3. Bind events and listeners in EventServiceProvider, or use automatic discovery mechanism; 4. Use event() or dispatch() to trigger events; 5. The listener can implement asynchronous processing, just add the ShouldQueue interface. This mechanism improves code clearance

How to compile assets with Laravel Mix?How to compile assets with Laravel Mix?Jul 23, 2025 am 03:01 AM

LaravelMixsimplifiesassetcompilationforLaraveldevelopersbyabstractingWebpackcomplexities.Togetstarted,installitvianpminstalllaravel-mix--save-devandcreateawebpack.mix.jsfile.Thendefineyourassetsourcesandoutputpathslikemix.js('resources/js/app.js','pu

Difference between `make()` and dependency injection via type-hinting in Laravel.Difference between `make()` and dependency injection via type-hinting in Laravel.Jul 23, 2025 am 02:56 AM

Thedifferencebetweenmake()andtype-hintedinjectioninLaravelliesintheirusageandimpactoncodedesign.1.make()manuallyresolvesaclassviathecontainer,oftenusedinclosuresorlegacycodeforconditionalinstantiationbutcanleadtotightercouplingandhiddendependencies.2

How to set up Laravel queues with Redis?How to set up Laravel queues with Redis?Jul 23, 2025 am 02:50 AM

TosetupLaravelqueueswithRedis,firstinstallandconfigureRedisonyourserverorlocalenvironment,usingcommandslikesudoaptinstallredisforUbuntu/DebianorbrewinstallredisformacOS,thenstarttheRedisserver.Second,configurethequeuedriverinLaravelbysettingQUEUE_CON

How to group routes in Laravel?How to group routes in Laravel?Jul 23, 2025 am 02:40 AM

When organizing a large number of routes in Laravel, you can use routing groups to classify and manage them by modules, middleware, prefixes, etc. to improve code maintainability. 1. Use prefix to group by prefix, such as classifying background routes to /admin; 2. Use middleware to uniformly add middleware to multiple routes, such as auth or combined middleware; 3. Use namespace to specify the controller directory for easy modular management; 4. You can combine prefix, middleware and namespace to achieve a clear and efficient routing organization method.

How to define an optional route parameter in Laravel?How to define an optional route parameter in Laravel?Jul 23, 2025 am 02:39 AM

The methods for defining optional routing parameters in Laravel are as follows: 1. Add ? after the routing parameters to indicate optional, such as {name?}; 2. Set default values for parameters in the controller or closure to avoid errors; 3. Optional parameters must be at the end of the route to ensure correct resolution; 4. When using named routes, you can generate links by omitting parameters or leaving empty array items. Through these steps, optional parameters can be handled flexibly and avoid common problems such as parameter order errors or type prompt conflicts.

Writing Unit and Feature Tests in Laravel.Writing Unit and Feature Tests in Laravel.Jul 23, 2025 am 02:38 AM

ThemaindifferencebetweenunitandfeaturetestsinLaravelisthatunittestsfocusonisolatedcomponentslikeclassesormethods,whilefeaturetestssimulateuserinteractions.Unittestscheckinternallogicsuchasamethodreturningthecorrectvalue,arefast,anddonotinvolveHTTPreq

How to debug a Laravel application?How to debug a Laravel application?Jul 23, 2025 am 02:28 AM

The key points of debugging Laravel applications include: 1. Turn on debug mode, set APP_DEBUG=true through the .env file to display detailed error information; 2. Use Log::info() and dd() to view variable content; 3. Check storage/logs/laravel.log log file to track exceptions and queries; 4. Enable DB::enableQueryLog() to check SQL query performance problems; 5. Install the LaravelDebugbar plug-in to improve debugging efficiency. These methods can help quickly locate and solve problems in development.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools