SQLSTATE [23000]:违反完整性限制:1062 'mail@mail.com' 'users_email_unique' 键的重复条目
Posted
技术标签:
【中文标题】SQLSTATE [23000]:违反完整性限制:1062 \'mail@mail.com\' \'users_email_unique\' 键的重复条目【英文标题】:SQLSTATE [23000]: Integrity limitation violation: 1062 'mail@mail.com' duplicate entry for 'users_email_unique' keySQLSTATE [23000]:违反完整性限制:1062 'mail@mail.com' 'users_email_unique' 键的重复条目 【发布时间】:2020-10-16 17:33:08 【问题描述】:我有一个注册表。当电子邮件在数据库中注册时,它会收到一条错误消息
SQLSTATE [23000]: Violation of integrity restrictions: 1062 Duplicate entry 'mail@mail.com' for 'users_email_unique' key
我想避免这个错误,而是收到类似“注册电子邮件”或类似内容的警告。任何帮助表示赞赏。这是我的代码。
controller/auth/registercontroller.php
<?php
namespace VMS\Http\Controllers\Auth;
use VMS\User;
use VMS\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
$this->middleware('guest');
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
return Validator::make($data, [
'name' => 'required|min:4',
'id_level' => 'required',
'email' => 'required|min:4|email|unique:users',
'password' => 'required',
'confirm' => 'required|same:password',
'g-recaptcha-response' => 'required|captcha',
]);
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \VMS\User
*/
protected function create(array $data)
return User::create([
'name' => $data['name'],
'id_level' => $data['id_level'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
public function store(Request $request)
$name = $request->input('name');
$id_level = $request->input('id_level');
$email = $request->input('email');
$password = $request->input('password');
$user = User::create([
'name' => $name,
'id_level' => $id_level,
'email' => $email,
'password' => Hash::make($password)
]);
if($user)
return response()->json([
'success' => true,
'message' => 'Register Berhasil!'
], 201);
else
return response()->json([
'success' => false,
'message' => 'Register Gagal!'
], 400);
User.php(模型)
<?php
namespace VMS;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'id_level', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $connection = 'vms_db';
register.blade.php
<!DOCTYPE html>
<html lang=" str_replace('_', '-', app()->getLocale()) ">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content=" csrf_token() ">
<title>SI-BeLa</title>
<!-- Scripts -->
<script src=" asset('js/app.js') " defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
<!-- Styles -->
<link href=" asset('css/app.css') " rel="stylesheet">
</head>
<body>
<div id="app">
<main class="py-4">
<div class="container" style="margin: 0; min-width: 100%">
<div class="row">
<div class="col-sm-6" style="text-align: ; padding-right: 20px;">
@guest
<a class="logo" href=" url('/') "> __('SI-BeLa') </a>
@endguest
</div>
<div class="col-sm-6" style="text-align: center;">
<h2 class="title">
<br><br>
<div style="text-align: center;">REGISTER
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li> $error </li>
@endforeach
</ul>
</div>
@endif
<form action=" route('register') " method="post">
csrf_field()
<div class="cont_form_sign_up text-center">
<br>
<input type="text" class="form-control2" placeholder="Nama" id="name" name="name" pattern=".4," required="required" title="Paling sedikit 4 karakter">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Nama paling sedikit 4 Karakter</p>
<input type="hidden" class="form-control2" value="9" id="id_level" name="id_level">
<input type="email" class="form-control2" placeholder="E-mail" id="email" name="email" required="required" pattern="[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Email harus aktif & Pastikan email belum terdaftar di SIBeLa</p>
<input type="password" id="pw1" name="password" class="form-control2" placeholder="Password"
required="required" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).8,">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Password paling sedikit 8 karakter serta mengandung angka, huruf kecil dan besar</p>
<input type="password" id="pw2" name="confirm" class="form-control2" placeholder="Confirm Password" required="required">
<div class="form-group">
<center>
!! NoCaptcha::renderJs() !!
!! NoCaptcha::display() !!
<span class="text-danger"> $errors->first('g-recaptcha-response') </span>
</center>
</div>
<a class="btn btn-linkk" href="/loginpl">
__('Kembali ke login')
</a>
<br>
<button class="button gd-btn btn-2 btn-primaryy" onclick="cambiar_sign_up()"><strong>REGISTER</strong> </button>
</div>
</form>
</div>
</h2>
</div>
</div>
</div>
</main>
如果邮箱已注册,如何发出通知提醒?
【问题讨论】:
【参考方案1】:你必须像这样使用。从验证中删除unique:users
return Validator::make($data, [
'name' => 'required|min:4',
'id_level' => 'required',
'email' => 'required|min:4|email',
'password' => 'required',
'confirm' => 'required|same:password',
'g-recaptcha-response' => 'required|captcha',
]);
【讨论】:
【参考方案2】:您必须在控制器中使用 laravel 验证来验证请求参数。
首先在你的控制器顶部添加这个使用
use Illuminate\Support\Facades\Validator;
然后在你的 registercontroller 中定义这个方法
public function register(Request $request)
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'password' => 'required|max:10',
'name' => 'nullable|string|max:50',
]);
if ($validator->fails())
$response = $validator->errors();
session()->flash('flash_error', $response);
return redirect()->back();
/**
* create new user
*/
try
/**
* new user
*/
User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
catch (Exception $e)
throw new HttpException(500, $e->getMessage());
session()->flash('flash_success', 'you are registered.');
return redirect()->back();
默认情况下,laravel 中的电子邮件字段是唯一的,为了验证它,我们使用此异常:
unique:users
users
是表名。
了解有关 laravel 验证的更多信息
查看此链接 https://laravel.com/docs/7.x/validation
访问视图文件中的验证错误
我们通过名称为flash_error
的错误闪存会话
你可以像这样展示它:
@if(session()->has('flash_error'))
<ul>
@foreach(session()->get('flash_error') as $error)
<li> session()->get('flash_error') </li>
@endforeach
</ul>
@endif
并像这样使用引导程序显示成功消息:
@if(session()->has('flash_success'))
<div class="alert alert-success" role="alert">
session()->get('flash_success')
</div>
@endif
【讨论】:
以上是关于SQLSTATE [23000]:违反完整性限制:1062 'mail@mail.com' 'users_email_unique' 键的重复条目的主要内容,如果未能解决你的问题,请参考以下文章
SQLSTATE [23000]:违反完整性约束:4025 CONSTRAINT
laravel 8 播种,SQLSTATE[23000]:违反完整性约束:
SQLSTATE[23000]:违反完整性约束:在 Laravel 5.2 中
SQLSTATE [23000]:违反完整性约束:1052 where 子句中的列 'tenant_id' 不明确
Laravel JOIN SQLSTATE [23000] 问题:违反完整性约束:字段列表中的 1052 列“album_id”不明确