您可以编写自定义验证程序规则。该规则可能是这个样子:
'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。我将把这个课程放在laravel 5.1中? – 2015-07-27 22:44:40
@MikeA查看[自定义验证规则文档](http://laravel.com/docs/5.1/validation#custom-validation-rules)。 – Bogdan 2015-07-28 00:22:10