Laravel 4 validation email unique constraint
Asked Answered
W

2

5

I'm writing a Laravel 4 app that has a users table with the usual contact info. In my users model, my validation for the email specifies 'email'=>'required|email|unique:users', which works fine when registering new users.

My question is how to handle the user edit form-- when the form is submitted, I'd like for the unique email constraint to only be fired if it's not the same as the old email-- otherwise you can't save your profile, since the email (your email) is already inuse.

Thanks

Wildee answered 26/1, 2015 at 4:15 Comment(0)
A
8

The third parameter to the unique rule allows you to specify an id of a record to ignore. When you're editing a user, you want your unique validation rule to ignore the value contained by the id of the user you are editing.

'email'=>'required|email|unique:users,email,'.$userId

You can see the docs on the validation rule here.

The trickiest part you'll run into is figuring out how to edit your rule to provide the id of the user you're editing. That all depends on how you have your rules set up and where you're doing your validation.

Airfoil answered 26/1, 2015 at 4:36 Comment(3)
You can always concat the Auth::user()->id since the user will be signed in to edit the recordVeneration
Getting the id isn't necessarily the tricky part. It is injecting the id into the rule that some people have issues with, just based on how or where their rules are defined and used. For example, if your rules are defined as a static attribute on the model, you'd need to have some type of placeholder in the rule, and then a method to replace that placeholder with a specific id, as described in this question/answer.Airfoil
I see your point but in that case it would be up to the OP to pass the ID to the function to complete the validation rules. Hopefully he'll do that. But it seems like this is the way to go, given the way he set this up.Veneration
V
2

Unique Validation Syntax

unique:table,column,except,idColumn

Try this to exclude the current email

unique:'users', 'email', Auth::user()->email

Veneration answered 26/1, 2015 at 4:25 Comment(2)
@rafael-- thanks but that's not really what I mean. If [email protected] registers a new account, the validation works fine. If he then submits an edit form and does no change his email, the validation fails since the email is in use, therefore it's not unique.Wildee
In the migration and or database you should set the email field to be uniquely indexed. That way the database can handle this kind of thing and not the validator. $table->unique('email'); Laravel Schema builderVeneration

© 2022 - 2024 — McMap. All rights reserved.