I want to validate Email column and Phone No column as Unique. Phone no is submitted to the Database as a concatenation of calling code and phone no. Here is my code.
public function customRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'country' => 'required',
'phone_no' => 'required|unique:users',
'password' => 'required',
]);
$data = $request->all();
$check = $this->create($data);
return redirect('login')->with('message', 'Signing up successful !!!');
}
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'country' => $data['country'],
'phone_no' => $data['calling_code'] . '-' . $data['phone_no'],
'password' => Hash::make($data['password']),
]);
}
In above code email validation is working perfectly. But the same phone no can be submitted to the DB. The validation rule is not working on the phone no. I couldn’t find where the error is.
Where should I change to validate the phone no as unique?
2
Answers
EDIT:
(Thanks to @brombeer, I noticed you are inserting values by concatenating, while comparing the initial value with that of concatenated already in database, which means you did not enforce uniqueness in database)
so, you can do it like the beautiful accepted answer or you can just go with a validating it like,
You may choose to create a Custom Validation Rule to validate the uniqueness of the phone number.
app/Rules/UniquePhoneNumber.php
Then make use of the new Custom Validation Rule: