首页 > 解决方案 > 如何使用 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外观进行这种验证?

标签: phplaravelvalidationlaravel-5.8

解决方案


您可以使用闭包创建自定义规则:

$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]');
            }

        },
    ],
]);

推荐阅读