php - 如何在 laravel 中处理重复条目

标签 php mysql json laravel api

在这里,我面临着数据库中重复条目的问题。我在我的 Controller 中设置了一个唯一的患者 ID,我想添加具有相同电子邮件地址但电话号码唯一的用户。

我在我的 Controller 功能中所做和尝试的事情:

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);
    }
}

一切都按照我的要求工作正常,但代码抛出以下异常:

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

这是我对 patients 表的迁移:

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();
});

最佳答案

您可以使用 laravel 验证来检查特定表中的唯一性。

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

关于php - 如何在 laravel 中处理重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50015892/

相关文章:

php - 修改 YAML 对真值和假值的解析

php - 将选择表单的值插入mysql

MYSQL Left Join 条件或

mysql - 在 SQL 查询中组合 "replace"和通配符

javascript - angular.fromJson 和 $scope.$eval 应用于 JSON 字符串时的区别

php - 如何使用 php 提交 github

php - 显示当前好友列表

json - 为嵌套的json数据创建Hive表

javascript - 将 JSON(jQuery) 发送到 PHP 并对其进行解码

javascript - 如何重定向页面