0

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

andrea created at6 years ago view count: 2716

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

report
回复
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);

});
6 years ago 回复

Recent search keywords