How to add combined unique fields validator rule in Laravel 4

前端 未结 2 439
暖寄归人
暖寄归人 2021-01-01 05:16

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 | totalmark

2条回答
  •  心在旅途
    2021-01-01 06:07

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

提交回复
热议问题