SQLSTATE [23000]:违反完整性限制:"users_email_unique"键的1062个"mail@mail.com"重复项 [英] SQLSTATE [23000]: Integrity limitation violation: 1062 'mail@mail.com' duplicate entry for 'users_email_unique' key
问题描述
我有一张注册表.当电子邮件在数据库中注册后,它会收到一条错误消息
I have a registration form. When the email is registered in the database it gets an error message
SQLSTATE [23000]: Violation of integrity restrictions: 1062 Duplicate entry 'mail@mail.com' for 'users_email_unique' key
我想避免该错误,而是收到类似已注册电子邮件"的警告.或类似的东西.任何帮助表示赞赏.这是我的代码.
I want to avoid that mistake and instead get a warning like "registered email" or something similar. Any help is appreciated. This is my code.
controller/auth/registercontroller.php
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(模型)
User.php (Model)
<?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
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>
如果电子邮件已注册,如何发出通知警报?
How do I make a notification alert if the email is registered?
推荐答案
您必须在控制器中使用laravel验证来验证请求参数.
you must use laravel validation in your controller for validate request parameters.
首先在您的控制器顶部添加此使用
first add this use top of your controller
use Illuminate\Support\Facades\Validator;
然后在您的registercontroller中定义此方法
then in your registercontroller define this method
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中的电子邮件字段是唯一的,为了验证它,我们使用此异常:
by default email field in laravel is unique and for validate it we use this exception :
unique:users
users
是表名.
了解有关laravel验证的更多信息
to learn more about laravel validation
查看此链接 https://laravel.com/docs/7.x/validation
访问视图文件中的验证错误
我们通过名称为flash_error
的错误Flash会话进行传递
您可以像这样显示它:
to access validation errors in view file
we pass errors flash session with name flash_error
you can show it for example like this:
@if(session()->has('flash_error'))
<ul>
@foreach(session()->get('flash_error') as $error)
<li>{{ session()->get('flash_error') }}</li>
@endforeach
</ul>
@endif
并使用以下引导程序显示成功消息:
and show success message with bootstrap like this:
@if(session()->has('flash_success'))
<div class="alert alert-success" role="alert">
{{ session()->get('flash_success') }}
</div>
@endif
这篇关于SQLSTATE [23000]:违反完整性限制:"users_email_unique"键的1062个"mail@mail.com"重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!