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条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算