【问题标题】:Laravel Validation Two ColumnsLaravel 验证两列
【发布时间】:2020-06-10 07:12:46
【问题描述】:

如何在请求验证中合并两列唯一的 together 以同时添加和更新? 最少 代码量。

【问题讨论】:

标签: laravel validation


【解决方案1】:

您可以通过以下语法忽略特定的 id

'email' => 'unique:table,email_column_to_check,id_to_ignore'

更多信息可以查看官方documentation

【讨论】:

    【解决方案2】:

    您可以通过扩展 Validator 类来创建自定义验证器。

    <?php
    // rules define for the particular request.
    public function rules() {
        \Validator::extend( 'composite_unique', function ( $attribute, $value, $parameters, $validator ) {
    
                // remove first parameter and assume it is the table name
                $table = array_shift( $parameters ); 
    
                // start building the conditions
                $fields = [ $attribute => $value ]; // current field, company_code in your case
    
                // iterates over the other parameters and build the conditions for all the required fields
                while ( $field = array_shift( $parameters ) ) {
                    $fields[ $field ] = $this->get( $field );
                }
    
                // query the table with all the conditions
                $result = \DB::table( $table )->select( \DB::raw( 1 ) )->where( $fields )->first();
    
                return empty( $result ); // edited here
            }, 'your custom composite unique key validation message' );
    
        return [
            'account_name' => 'required|min:5|max:100',
            'legal_name'   => 'max:100',
            // note that here the custom validator is used
            'company_code' => 'required|size:18|composite_unique:accounts,client_id', 
            'client_id'    => 'required|min:1',
        ];
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-05
      • 2017-11-10
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多