Laravel unique validation rules not working on update method - Solution

Problem:

Laravel unique validation rules not working on update method. How can I do that.


Solution:

First say, let a user table with column name, email, username and password. When we store this in the user's table just use this simple validation and it's working.
$this->validate($request, array(
 'name' => 'required|min:3|max:20',
 'email' => 'required|max:50|email|unique:users, email',
 'username' => 'required|alpha_num|unique:users, username',
 'password' => 'required|min:6|max:20'
));

Hope that's working in your case.
But when try to execute the same code in updating that values without any change on that email and username. Then get the error -
The username has already been taken.
The email has already been taken.

So, What can we do is -
When validate a tables value if unique then pass the extra id of that row with that unique. Then everything will be clear and the errors username already taken or email already taken will be gone.

$id = 2;
$this->validate($request, array(
 'name' => 'required|min:3|max:20',
 'email' => 'required|max:50|email|unique:users, email,' .$id,
 'username' => 'required|alpha_num|unique:users, username,' .$id,
 'password' => 'required|min:6|max:20'
));

So, first get the ID and in update case, obviously you get the ID as a parameter of that function, just pass that with unique attributes and error will gone.


My Experience:
At first, I've got the error and having much trouble and now I can take any update action and use the validation rule properly.


Tags:
Laravel Validation, Laravel On update validation problem, Laravel unique validation rules not working on update method, Laravel Unique validation problems, Laravel validation solution in unique attributes.
Laravel unique validation rules not working on update method - Solution Laravel unique validation rules not working on update method - Solution Reviewed by Maniruzzaman Akash on October 14, 2017 Rating: 5

3 comments:

  1. For organization issues, I'm trying to do these validations inside my ObjectRequest, but I'm not getting it because I do not know how to pass ID of that object. Have you been through this too?

    ReplyDelete
  2. Thanks for sharing the useful blog about the Issue on "unique validation rules not working on update method" in Laravel.

    Web Application Development Company in Coimbatore

    ReplyDelete

Powered by Blogger.