How to add combined unique fields validator rule i

2019-02-14 14:34发布

I am using Laravel 4.2 and mysql db .
I have an exam table in which i am taking Exams entry and the fields are -->
id | examdate | batch | chapter | totalmarks

I have made a combined unique key using
$table->unique( array('examdate','batch','chapter') ); in schema builder.
Now I want to add a validation rule to it. I know i can add unique validation by laravel unique validator rule but the problem is ,it checks only for one field .
I want it to add uniqueness to the 3 fields combined(user must not be able to add second row with same value combination of examdate,batch and chapter fields).

Is it even possible to do it in laravel 4 .Is there any workaround if its not possible?

2条回答
乱世女痞
2楼-- · 2019-02-14 15:22

It didn't work for me so I adjusted the code a tiny bit.

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

The validator looks like this. You don't need a particular order of DB table column names as stated in the other answer.

$validator = Validator::make($request->all(), [
        'attributeName' => 'unique_multiple:tableName,field[1],field[2],....,field[n]'
    ],[
        'unique_multiple' => 'This combination already exists.'
    ]);
查看更多
聊天终结者
3楼-- · 2019-02-14 15:29

You could write a custom validator rule. The rule could look something like this:

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

The code for that would look something like this:

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

You can use as many fields as you like for the condition, just make sure the value passed is an array containing the values of the fields in the same order as declared in the validation rule. So your validator code would look something like this:

$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'
    )
);
查看更多
登录 后发表回答