Laravel用户注册:自定义字段是唯一的验证



我正在尝试在数据库中使用相同的电子邮件添加更多用户,从而禁用了电子邮件,并为该[帐户] ...

添加了另一列列

注册表格还包括此字段,

<input type="text" name="account" required hidden value="{{getUUid()}}"/>
@if ($errors->has('account'))
   <span class="help-block">
   <strong>{{ $errors->first('account') }}</strong>
</span>
@endif

所有,所有这些都在数据库中正确存储,并带有多个用相同电子邮件的用户。我面临的问题与验证有关;将registercontroller.php更改为

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255',
        'password' => 'required|string|min:6|confirmed',
        'account' => 'required|unique:users|max:50',
    ]);
}

并创建功能到

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'account' => (getEvent()->hash.'_'.$data['email']),           
    ]);
}

实际上有一个重复时,我有一个错误500,数据库错误

Illuminate  Database  QueryException (23000)
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry for key 'users_account_unique'

我是Laravel的新手,不明白我缺少执行电子邮件验证相同行为并防止数据库错误的其他内容。

*已解决 * 用中间件重定向以注册用户是否已经存在。

以下行正在引起您的问题,因为它会产生重复结果 -

(getEvent()->hash.'_'.$data['email'])

您无法验证 account 字段 form验证,因为它不是来自表单数据,因此将稍后生成。但是您可以手动检查此 -

$user = User::where('account','=',(getEvent()->hash.'_'.$data['email']))->first();
if($user!=null){
     return back()->withInput()->with('errorMessage','Account already Exists!!');
}
return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
    'account' => (getEvent()->hash.'_'.$data['email']),           
]);

最新更新