duanpao4522 2017-11-27 19:04
浏览 160

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

I am trying to add more users with the same email in the database disabling the unique for email, adding another column for that [account]...

The registration form also includes this field,

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

and all is stored correctly in the database, with multiple users with same email. The problem I am facing is related to the validation; changed RegisterController.php to

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

and create function to

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

    ]);

}

when actually there is a duplicate I am having an error 500 with the database error

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

I am new to Laravel and don't understand what else I am missing to perform the same behavior of the email validation and prevent the database error.

* Solved * with a middleware redirecting to register if the user already exists.

  • 写回答

1条回答 默认 最新

  • dongmian8108 2017-11-27 19:42
    关注

    Following line is causing you the problem as it's producing duplicate result-

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

    You can't validate account field like form validation as it is not coming from form data, it is generated later. But you can check this manually-

    $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']),           
    
    ]);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题