Validation problem on edit with duplicated email addresses (unique values required)
I am building a CMS system, where an admin can add a new user to the system fine (name, email etc..).
When I am trying to edit a user the issue I get is if a user being edited by the admin uses an existing email address in the database I get the following MySQL error.
I want to have the error gracefully to the Laravel errors array rather than an Exception, so it would use the validation to use some custom logic which checks if the email exists if so to have an error 'email already exists to another user'
Can anyone suggest how I should do this?
public function store(Request $request)
{
$this->validate($request, [
'email' => 'required|email|unique:users'
]);
}
You have to tell the Validator to ignore the currently edited user's id when it check the uniqueness of the email. Laravel allows you to do that like this:
use Illuminate\Validation\Rule; // don't forget to import this class at the top of your file
public function store(Request $request)
{
$this->validate($request, [
'email' => [
'required',
'email',
Rule::unique('users')->ignore($userId),
]);
}