使用枚举列进行 Laravel 验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43317806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel validation with enum column
提问by Payam Khaninejad
I have this fields:
我有这个领域:
id, title, type
ID,标题,类型
type is enum And I would like to validate my title by Type column, eg:
type 是 enum 我想通过 Type 列验证我的标题,例如:
id | title | type
1 | test | option1
2| test | option2
So when someone tries to insert a row with this condition, validation should be processed for unique of the column.
因此,当有人尝试插入具有此条件的行时,应针对该列的唯一性处理验证。
3 | test | option1 ==> should not be insert due unique validation rule.
How will my validation rule look like?
我的验证规则会是什么样子?
Regards
问候
// Edit 1: Rules facade was the solution.
// 编辑 1:规则外观是解决方案。
回答by APu
in:option1,option2The field under validation must be included in the given list of values.
in:option1,option2验证字段必须包含在给定的值列表中。
not_in:option1,option2The field under validation must not be included in the given list of values.
not_in:option1,option2验证字段不得包含在给定的值列表中。
You'r validation should look like the following, but it requires your to hard code your options in "in" parameters or 'implode' an array.
您的验证应如下所示,但它要求您在“in”参数或“内爆”数组中对您的选项进行硬编码。
$validator = Validator::make(Input::only(['title', 'type']), [
'type' => 'in:option1,option2, // option1 or option2 values
'title' => 'required|min:6|max:255', //whatever rules you want ..
]);
You can avoid 'implode' by this way:
您可以通过这种方式避免“内爆”:
$validator = Validator::make(Input::only(['title', 'type']), [
'type' => Rule::in(['option1', 'option2']), // option1 or option2 values
'title' => 'required|min:6|max:255', //whatever rules you want ..
]);
回答by sazanrjb
If the type
field is not dynamic, you could use Rule
class to add extra query in your validation rule.
如果该type
字段不是动态的,您可以使用Rule
class 在验证规则中添加额外的查询。
return [
'title' => [
Rule::unique('tablename', 'title')->where(function ($query) {
$query->where('type', 'option1');
})
]
];
else, you can make custom validation rules.
否则,您可以制定自定义验证规则。
回答by Learner
There is no custom rule for that .
没有自定义规则。
You can not verify combination of two columns as unique by any laravel native validation rule.
您无法通过任何 Laravel 本机验证规则验证两列的组合是否唯一。
However you have got two options ahead:
但是,您有两个选择:
- Create your own rule using the a custom validator. Reference
- Use this package: https://github.com/felixkiss/uniquewith-validator
- 使用自定义验证器创建您自己的规则。参考
- 使用这个包:https: //github.com/felixkiss/uniquewith-validator
Of course make combination of title
and type
unique in you migration as well.
当然title
,type
在您的迁移中也可以组合和独特。