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

时间:2014-10-31 21:37:29

标签: mysql validation laravel laravel-4

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

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

甚至可以在laravel 4中进行。如果不可能,有任何解决方法吗?

2 个答案:

答案 0 :(得分:10)

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

'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'
    )
);

答案 1 :(得分: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);
 });

验证器看起来像这样。您不需要特定的DB表列名称顺序,如另一个答案中所述。

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