dseslyh6662605 2019-06-10 06:21
浏览 524
已采纳

如何避免Laravel验证规则中的重复

For validating form validation rules I currently stored them in User Model and use it in Register Controller, User controller in admin panel, User Controller in APIs and some other places, but currently it's very hard to maintain because each controller needs a slightly different set of rules and when I change the rules in User Model other controllers will not work anymore. So how to avoid duplication in rules and still keep the code maintainable?

  • 写回答

2条回答 默认 最新

  • duanliexi1052 2019-06-10 06:51
    关注

    Approach I often use is to write a HasRules trait for my models, it looks something like this:

    trait HasRules
    {
        public static function getValidationRules(): array
        {
            if (! property_exists(static::class, 'rules')) {
                return [];
            }
    
            if (func_num_args() === 0) {
                return static::$rules;
            }
    
            if (func_num_args() === 1 && is_string(func_get_arg(0))) {
                return array_get(static::$rules, func_get_arg(0), []);
            }
    
            $attributes = func_num_args() === 1 && is_array(func_get_arg(0))
                ? func_get_arg(0)
                : func_get_args();
    
            return array_only(static::$rules, $attributes);
        }
    }
    

    Looks messy, but what it does is allows you to retrieve your rules (from a static field if such exists) in a variety of ways. So in your model you can:

    class User extends Model
    {
        use HasRules;
    
        public static $rules = [
            'name' => ['required'],
            'age' => ['min:16']
        ];
    
        ...
    }
    

    Then in your validation (for example, in your FormRequest's rules() method or in your controllers when preparing rules array) you can call this getValidationRules() in variety of ways:

     $allRules = User::getValidationRules(); // if called with no parameters all rules will be returned.
    
     $onlySomeRules = [
         'controller_specific_field' => ['required'],
         'name' => User::getValidationRules('name'); // if called with one string parameter only rules for that attribute will be returned.
     ];
    
     $multipleSomeRules = User::getValidationRules('name', 'age'); // will return array of rules for specified attributes.
    
     // You can also call it with array as first parameter:
     $multipleSomeRules2 = User::getValidationRules(['name', 'age']);
    

    Don't be afraid to write some code for generating your custom controller specific rules. Use array_merge and other helpers, implement your own (for example, a helper that adds 'required' value to array if it's not there or removes it etc). I strongly encourage you to use FormRequest classes to encapsulate that logic though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角