您可以通过扩展 Validator 类来创建自定义验证器。
<?php
// rules define for the particular request.
public function rules() {
\Validator::extend( 'composite_unique', function ( $attribute, $value, $parameters, $validator ) {
// remove first parameter and assume it is the table name
$table = array_shift( $parameters );
// start building the conditions
$fields = [ $attribute => $value ]; // current field, company_code in your case
// iterates over the other parameters and build the conditions for all the required fields
while ( $field = array_shift( $parameters ) ) {
$fields[ $field ] = $this->get( $field );
}
// query the table with all the conditions
$result = \DB::table( $table )->select( \DB::raw( 1 ) )->where( $fields )->first();
return empty( $result ); // edited here
}, 'your custom composite unique key validation message' );
return [
'account_name' => 'required|min:5|max:100',
'legal_name' => 'max:100',
// note that here the custom validator is used
'company_code' => 'required|size:18|composite_unique:accounts,client_id',
'client_id' => 'required|min:1',
];
}