I created a registration page for my users but the email validation is not working, I cant display the alert that the email is already in use. What should I change with my code
Controller code
public function registerUser(Request $request)
{
// Validate form input
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'middle_name' => 'required',
'last_name' => 'required',
'birthdate' => 'required',
'email' => 'required|email|unique:user_models,email',
'password' => 'required|min:5|max:20'
], [
'first_name.required' => 'First name field is required',
'middle_name.required' => 'Middle name field is required',
'last_name.required' => 'Last name field is required',
'birthdate.required' => 'Birthdate field is required',
'email.required' => 'Email field is required',
'email.email' => 'Email field should be a valid email',
'email.unique' => 'The email has already been taken',
'password.required' => 'Password field is required',
'password.min' => 'Password should be at least 5 characters',
'password.max' => 'Password should be at most 20 characters',
]);
if ($validator->fails()) {
// Return validation error if input is invalid
return response()->json([
'status' => 400,
'errors' => $validator->messages(),
'message' => 'Please fix the following errors:',
])->withErrors($validator)->with('error', 'Please fix the following errors:');
}
else {
// Create new user model and save to database
$user = new UserModel();
$user->first_name = Str::ucfirst($request->input('first_name'));
$user->middle_name = Str::ucfirst($request->input('middle_name'));
$user->last_name = Str::ucfirst($request->input('last_name'));
$user->ip_address = $request->ip('ip_address');
$user->birthdate = $request->input('birthdate');
$user->email = Str::lower($request->input('email'));
$user->account_status = '1';
$user->password = Hash::driver('whirlpool')->make($request->password);
$user->save();
$seq_id = $user->seq_id;
$user->application_code ="AUP-M231-" . str_pad($seq_id, 6, '0', STR_PAD_LEFT);
$user->save();
// Create new ApplicantPPCModel and save to database
$user2 = new ApplicantPPCModel();
$user2->email = Str::lower($request->input('email'));
$user2->pc = $request->input('password');
$user2->seq_id = $user->seq_id;
$user2->save();
// Send activation email to user
$data = [
'title' => 'Welcome to Lorem Ipsum University',
'body' => 'Thank you for registering with us',
'activation_code' => $user->application_code,
'first_name' => $user->first_name
];
try {
Mail::to($user->email)->send(new MailNotify($data));
} catch (Swift_TransportException $e) {
// Return error response if email fails to send
return response()->json(['message' => 'Sorry! Please try again later'], 500);
}
// Return success response
return response()->json([
'status' => 200,
'message' => 'You have registered successfuly',
]);
}
}
Ajax Code
$.ajax({
type: "POST",
url: "/register-user",
data: data,
dataType: "json",
success: function (response) {
if(response.status == 400) {
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'That email is in use already. Please try another one',
})
}else {
$('.alert-success').removeClass('hideme');
setTimeout(function() {
$('.alert-success').fadeOut();
}, 3000);
$('#reg_first_name').val('');
$('#reg_middle_name').val('');
$('#reg_last_name').val('');
$('#reg_email').val('');
$('#birth_date').val('');
$('#reg_email_confirm').val('');
$('#reg_password').val('');
$('#reg_password_confirm').val('');
$('#reg_id_number').val('');
$( "#checkbox-signup" ).prop( "checked", false );
$( "#btn-register" ).prop( 'disabled', true );
Swal.fire("You're Registered!", "Please check your email before proceeding to the Login Page", "success")
}
}
});
Network message
"message": "SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "the_email"nDETAIL: Key (email)=([email protected]) already exists.
I can display the sweet alert when a user registers successfully but i cant display any error message that will alert the user with the registration.
2
Answers
It seems that your ‘unique’ validation rule for ’email’ is not working, so you get SQLSTATE[23505] and i think a 500 response.
Check the table name and the column name in the validation rule and also, if you are updating, add an ignore condition.
Then i tink you can refactor the validation response like this:
Reponse::class is SymfonyComponentHttpFoundationResponse
Then you have to add an error(xhr,status,error) entry to the ajax call to manage responses with error codes (not 200), in this way you can trap 400 BAD REQUEST and also 500 INTERNAL SERVER ERROR
Because when the email already exists the validation you wrote doesn’t treat that so the validation doesn’t fail which means it goes directly to try creating a new user but it fails because in real the email already exists in the database
Solution:
verify the table name if it’s correct
verify the column name if it’s correct
replace the table name with the path of the model
’email’ => ‘unique:AppModelsUserModel,email’