0

Laravel 验证多个字段在数据库表中唯一

andrea 发布于2年前 阅读数 2313

现在有针对一个字段的唯一验证"label"=>"required|unique:tablename' 不知道多个字段怎样写的规则。

举报
回复
0

网上找了段代码。需要自定义个验证规则。

protected $rules = [
    'user_id' => 'unique_multiple:memberships,user_id,group_id',
    'group_id' => 'unique_multiple:memberships,user_id,group_id',
]

/**
 * Validates that two or more fields are unique
 */
Validator::extend('unique_multiple', function ($attribute, $value, $parameters, $validator)
{
    //if this is for an update then don't validate
    //todo: this might be an issue if we allow people to "update" one of the columns..but currently these are getting set on create only
    if (isset($validator->getData()['id'])) return true;

    // Get table name from first parameter
    $table = array_shift($parameters);

    // Build the query
    $query = DB::table($table);

    // Add the field conditions
    foreach ($parameters as $i => $field){
        $query->where($field, $validator->getData()[$field]);
    }

    // Validation result will be false if any rows match the combination
    return ($query->count() == 0);

});
2年前 回复