php - 如何使用 laravel Rule 门面将请求字符串与表中最后插入的行进行比较
问题描述
我有验证电话确认代码的自定义代码:
代码:
$validator = Validator::make($request, [
'confirm_code' => [
'required',
Rule::exists('confirm_codes')->where(function($query) use($request) {
$query->where('phone', $request->phone)
->where('confirm_code', $request->confirm_code)
})
]
]);
此验证有效,但检查现有的任何确认代码,哪个电话等于请求电话。但我需要检查请求确认代码和最后插入的确认代码,从表confirm_codes
中哪个电话等于请求电话。
试过:
Rule::exists('confirm_codes')->where(function($query) use($request) {
$query->where('phone', $request->phone)
->where('confirm_code', $request->confirm_code)
->orderBy('created_at', 'desc'); // added this line <--
})
但是这个解决方案不起作用。我怎样才能使用Rule
外观进行这种验证?
解决方案
您可以使用闭包创建自定义规则:
$validator = Validator::make($request, [
'confirm_code' => [
'required',
function ($attribute, $value, $fail) {
$latest = DB::table('confirm_codes')->latest()->first();
if ($request->phone === $latest->phone && $value === $latest->confirm_code) {
$fail('[enter your error message here]');
}
},
],
]);
推荐阅读
- c# - 如何创建接受多个值并序列化为 WinForms Form.designer.cs 的 TypeConverter?
- moving-average - 需要在 MA 交叉和下一个蜡烛关闭>打开后进入交易
- sql - 在表列 oracle 中混淆名称
- swiftui - WidgetKit 正确的占位符
- sybase - 无法在 SYBASE ASE 中创建具有最大长度的列
- java - 如何处理找不到字段的映射以便在java中对异常进行排序
- python - 如何在 StepFunction 名称中使用 CloudFormation 参数
- pine-script - 不能用 'symbol'=series[string] 调用 'security'。参数的类型应该是:字符串;
- perl - 当输入文件为空时,用于向文件添加标题的 Perl 简单单行器不起作用
- flutter - 如何针对正则表达式验证 textField 并在颤动中显示错误消息