如何为4个组合的唯一列创建自定义验证规则 [英] How to create custom validation rule for 4 combinedly unique columns
问题描述
由于Laravel的默认 unique:tablename
验证规则仅允许两列;在两个以上的唯一列的情况下,它直接使用
Since Laravel's default unique:tablename
validation rule allows only two columns; in scenarios where more than two columns are unique, it directly throws the QueryException
with SQLSTATE errorcode 23000. As a temporary workaround I am catching the exception and throwing a warning like this:
try{
//My query that might throw an exception for a duplicate entry
} catch (\Exception $e){
return $e->getCode() == 23000 ?
redirect()->back()->with('warning','Duplicate entry') :
redirect()->back()->with('error','Unknown Error Occurred');
}
问题是,对于其他所有错误代码不是23000的情况,我只会看到一条错误消息Unknown Error Occurred
而不是
The problem is, for every other scenarios where the errorcode is not 23000, I will only see an error message Unknown Error Occurred
instead of Whoops. Clearly, debugging will be a nightmare.
所以我在寻找替代方案.我必须选择两个选项之一:a)使用第三方软件包,或者,b)创建自定义验证规则
So I looked for alternatives. I had to pick one of two options: a) Use a third party package or, b) Create a custom validation rule
我选择了选项b.但是我在为自己打造自己而苦苦挣扎.当我看一个示例(一次内联规则)时:
I chose option b. But I am struggling with how I can construct one myself. When I looked at an example (for one-time inline rule):
$validator = Validator::make($request->all(), [
'title' => [
'required',
'max:255',
function($attribute, $value, $fail) {
if ($value === 'foo') {
return $fail($attribute.' is invalid.');
}
},
],
]);
...我意识到该规则只能应用于单个属性和值.但是我有4个属性和值来检查它们是否确实是唯一条目.我该怎么办?
...I realized that the rule can be applied to a single attribute and value only. But I have 4 attributes and values to check if they are indeed a unique entry. How can I do that?
推荐答案
我这样使用,
public function store(Request $req)
{
$column1 = $req->input('column1');
$column2 = $req->input('column2');
$column3 = $req->input('column3');
$column4 = $req->input('column4');
$whereData = [
['column1', $column1],
['column2', $column2],
['column3', $column3],
['column4', $column4]
];
$count = DB::table('yourtablename')->where($whereData)
->count();
if($count > 0){
// The combined is not unique
//send error message
}else{
//do whatever u need
}
}
您也可以在AppServiceProvider
的启动方法中实现此功能.
You may implement this in AppServiceProvider
's boot method also.
将此代码添加到您的启动方法中:
Add this code to your boot method:
Validator::extend('uniqueofFourColumns', function ($attribute, $value, $parameters, $validator) {
$whereData = [
['column1', $value],
['column2', $parameters[0]],
['column3', $parameters[1]],
['column4', $parameters[2]]
];
$count = DB::table('yourtablename')->where($whereData)->count();
return $count === 0;
});
然后您可以在需要的地方使用uniqueofFourColumns
此规则:
Then u may use uniqueofFourColumns
this rule wherever u need:
'column1' => 'uniqueofFourColumns:'.{{$request->column2}}.', '.{{$request->column3}}.', '.{{$request->column4}}
这篇关于如何为4个组合的唯一列创建自定义验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!