dongpin1850 2018-04-25 06:57
浏览 72
已采纳

如何对抗laravel中的重复输入

Here I am facing an issue of duplicate entries in my database. I have setup a unique patient ID in my controller and I want to add users having the same e-mail, but a unique phone number.

What I have done and tried in my controller function:

public function store(Request $request) {    
    $validator = \Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email',
        'phone'=>'required|min:11|numeric|unique:patients',
        'birth_date' => 'required',
        'gender' => 'required',
        'address' => 'required',
    ]);

    if ($validator->fails()) {
        $errors = $validator->errors();
        return $errors->toJson();
    } else {
        $fileNameToStore = 'defaultimg/avatar.png';
        $post = new patient;
        $post->name = $request->input('name');
        $post->email = $request->input('email');
        $post->picture = $fileNameToStore;
        $post->birth_date = $request->input('birth_date');
        $post->gender = $request->input('gender');
        $address = htmlspecialchars($request->input('address'));
        $post->address = $address;
        $post->patient_id = 'PID' . rand(999, 9999999999999);
        $post->phone = $request->input('phone');
        $post->save();

        return response(array(
            'error' => false,
            'message' => 'Patient added successfully', 'patientid' => $post->patient_id,), 200);
    }
}

Everything is working fine as per my requirement, but the code throws the following exception:

QueryException SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'front@gmail.com' for key 'patients_email_unique'

Here is my migration for the patients table:

Schema::create('patients', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('birth_date');
    $table->string('gender');
    $table->string('address');
    $table->string('patient_id');
    $table->string('picture');
    $table->string('phone')->unique();
    $table->rememberToken();
    $table->timestamps();
});
  • 写回答

4条回答 默认 最新

  • dou7851 2018-04-25 07:03
    关注

    Change this line

    $table->string('email')->unique();
    

    To

    $table->string('email');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?