Reputation: 75
I'm working on updating a user in Laravel, where I made the following validation rule for updating a users email:
"email" => "required|email|unique:users,email,".$this->route("user")->id,
This is inside of my form request. However, when I post, it still says that the email is already taken? Is this perhaps a bug in the latest version of Laravel?
Thanks!
Upvotes: 0
Views: 853
Reputation: 337
First you have to add rules in user model
static function rules() {
return [
'email' => 'required|email'
];
}
In user controller
use Illuminate\Validation\Rule; // add this one
function add_update_user(Request $request,$user_id) {
$data = $request->all();
unset($data['_token']);
$rules = User::rules();
$rules['email'] = explode('|', $rules['email']);
if (isset($user_id)) // is old user, your get user_id in route
{
$rules['unique_code'][] = Rule::unique('databse_connection_name.users')->ignore($data['email'], 'email');
} else // is new user
{
$rules['email'][] = 'unique:databse_connection_name.users,email';
}
$validator = Validator::make($data, $rules);
...
...
}
Upvotes: 0
Reputation: 1556
you set the ignore email column so you should pass email not id
"email" => "required|email|unique:users,email,".$this->route("user")->email,
Upvotes: 0
Reputation: 14278
No it is not a bug, you are using a null
value for the id hence the reason why, change your rule to this:
"email" => "required|email|unique:users,email,".$this->user()->id,
Make sure that you have Request $request
in your method, and also you have the auth middleware on your controller.
Upvotes: 1