How to add combined unique fields validator rule in Laravel 4

前端 未结 2 440
暖寄归人
暖寄归人 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:04

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

提交回复
热议问题