0
votes

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 '[email protected]' 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

<?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 (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

<!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>
</div>

enter image description here

3
so you are using your own "registration" functionality instead of using the out of the box functionality ... which out of the box uses validation to make sure that the email address is uniquelagbox
Simple, stop trying to submit a duplicate email address?GrumpyCrouton
I want to avoid that mistake and instead get a warning like "registered email" or something similar. Any help is appreciated. @lagboxyooyo
.@GrumpyCroutonyooyo
out of the box the validation checks that the email address is unique and if not returns a validation message, not an error ... that is what the unique rule is for with validationlagbox

3 Answers

0
votes

You have to validate your data before saving to the database. You are getting that error because there is no validation for unique email. You resolve it with the example below:

public function register(Request $request) {
 $validatedData = $request->validate([
    'email' => ['required', 'max:250', 'unique:users,email'],
     //it means that the field email is required, can I have up to 250 characters, the column email in table users must be unique;
  ]);
//** Store logic goes here
}
0
votes

You can catch this exception in your store or create method. Example:

public function store(Request $request)
{

    $name = $request->input('name');
    $id_level = $request->input('id_level');
    $email        = $request->input('email');
    $password     = $request->input('password');
    
    try {
    $user = User::create([
        'name'      => $name,
        'id_level'      => $id_level,
        'email'     => $email,
        'password'  => Hash::make($password)
    ]);
    } catch (\Exception $e) {
        $user =  null;
        //Error with $e->getMessage()
    }

if($user) {
    return response()->json([
        'success' => true,
        'message' => 'Register Berhasil!'
    ], 201);
} else {
    return response()->json([
        'success' => false,
        'message' => 'Register Gagal!'
    ], 400);
}
0
votes

Use like laravel default register form

  <div class="form-group row">
   <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

   <div class="col-md-6">
       <div class="{{'form-group required'.$errors->first('email',' has-error')}}">
          <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
       <span class="invalid-feedback" role="alert">
            <strong><div class="text-danger">{{$errors->has('email') ? $errors->first('email') : ''}}</div></strong>
       </span>
                            
    </div>
 </div>