如何在Laravel 4中添加组合的唯一字段验证器规则

Vis*_*air 4 mysql validation laravel laravel-4

我正在使用Laravel 4.2和mysql db.
我有一个考试表,我正在参加考试,字段是 - >
id | examdate | batch | chapter | totalmarks


$table->unique( array('examdate','batch','chapter') );在模式构建器中使用组合的唯一键.
现在我想为它添加一个验证规则.我知道我可以通过laravel唯一验证器规则添加唯一验证,但问题是,它只检查一个字段.
我希望它为3个字段组合添加唯一性(用户必须无法添加具有相同值组合的examdate,batch和chapter字段的第二行).

是否有可能在laravel 4中进行.如果不可能,有任何解决方法吗?

Bog*_*dan 10

您可以编写自定义验证程序规则.规则看起来像这样:

'unique_multiple:table,field1,field2,field3,...,fieldN'
Run Code Online (Sandbox Code Playgroud)

代码看起来像这样:

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);
});
Run Code Online (Sandbox Code Playgroud)

您可以根据需要使用任意数量的字段,只需确保传递的值是一个数组,其中包含的字段值与验证规则中声明的顺序相同.所以你的验证器代码看起来像这样:

$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'
    )
);
Run Code Online (Sandbox Code Playgroud)