2014-10-31 121 views
4

我正在使用Laravel 4.2和mysql db。
我考试表格中,我正在考试条目和字段 - >
id | examdate | batch | chapter | totalmarks如何在Laravel 4中添加组合的唯一字段验证器规则

我已在架构构建使用
$table->unique(array('examdate','batch','chapter'));组合唯一的密钥。
现在我想添加一个验证规则。我知道我可以通过laravel unique validator rule添加独特的验证,但问题是,它只检查一个字段。
我希望它为3个字段组合添加唯一性(用户不能添加具有相同的考试日期,批次和章节值组合的第二行)。

它甚至可以在laravel 4中执行它。如果它不可行,是否有任何解决方法?

回答

9

您可以编写自定义验证程序规则。该规则可能是这个样子:

'unique_multiple:table,field1,field2,field3,...,fieldN' 

该代码会是这个样子:

Validator::extend('unique_multiple', function ($attribute, $value, $parameters) 
{ 
    // 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, $value[$i]); 

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

,只要你喜欢的状态,您可以使用尽可能多的领域,只要保证值传递是一个包含字段值的数组,其顺序与验证规则中声明的顺序相同。所以你的验证代码看起来是这样的:

$validator = Validator::make(
    // Validator data goes here 
    array(
     'unique_fields' => array('examdate_value', 'batch_value', 'chapter_value') 
    ), 
    // Validator rules go here 
    array(
     'unique_fields' => 'unique_multiple:exams,examdate,batch,chapter' 
    ) 
); 
+0

这是很棒的+1。我将把这个课程放在laravel 5.1中? – 2015-07-27 22:44:40

+0

@MikeA查看[自定义验证规则文档](http://laravel.com/docs/5.1/validation#custom-validation-rules)。 – Bogdan 2015-07-28 00:22:10

0

它没有为我工作,所以我调整了一点代码。

Validator::extend('unique_multiple', function ($attribute, $value, $parameters, $validator) 
{ 
    // Get the other fields 
    $fields = $validator->getData(); 

    // 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, $fields[$field]); 
    } 

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

验证器看起来像这样。如其他答案中所述,您不需要特定的数据库表列名称顺序。

$validator = Validator::make($request->all(), [ 
     'attributeName' => 'unique_multiple:tableName,field[1],field[2],....,field[n]' 
    ],[ 
     'unique_multiple' => 'This combination already exists.' 
    ]);