首页 > 解决方案 > 验证年龄变量 - Laravel RegisterController

问题描述

我在 Laravel OOB 注册表单中添加了 3 个字段,它们是出生月份、日期和年份。我将这些字段传递给 RegisterController 中的验证器函数,并使用 Carbon 将它们转换为年龄:

$theAge = Carbon::createFromDate($data['birthyear'], $data['birthmonth'], $data['birthday'])->age;

这部分工作正常,我可以将变量传递给表中的字段并查看正确的年龄。

如何将 $theAge 添加到我的验证器?

return Validator::make($data, [
        'email' => 'required|string|email|max:255|unique:users|confirmed',
        'password' => 'required|string|min:8|confirmed',
        'first_name' => 'required|string|max:255',
        'last_name' => 'required|string|max:255',
        'address' => 'required|string|max:255',
        'city' => 'required|string|max:255',
        'state' => 'required|string|max:2',
        'zipcode' => 'required|string|max:10',
        'brand' => 'required',
        'opt_in' => 'required',
        'g-recaptcha-response' => 'required|captcha',
        'birthmonth' => 'required',
        'birthday' => 'required',
        'birthyear' => 'required',
    ]);

我尝试了以下方法,但在验证时似乎被忽略了:

$theAge => 'bail|min:21'

我已经研究了After Validation Hook,但不明白如何在我的情况下使用它。

标签: laravel

解决方案


您可以将 $theAge 变量添加到数据数组中。

$data['age'] = Carbon::createFromDate($data['birthyear'], $data['birthmonth'], $data['birthday'])->age;

推荐阅读