php - Validation fails in Unique constraint

Solution:
You've misunderstood the id parameter to theunique
rule a little bit. You need to pass in the id of the record you're updating, and then tell the unique rule to exclude that record id.
// $id should be the string 'NULL' if no id passed in
public static function rules($id = 'NULL') {
return array(
"name" => "required",
"username" => "required|unique:user,username,".$id.",id_user",
"email" => "required|email|unique:user,email,".$id.",id_user",
);
}
Explanation
For your existing implementation, if you were to look at your query log (DB::getQueryLog()
), you would see that the statement run for your name validation would be:
select count(*) as aggregate from `user` where `username` = 'vitorluis' and `username` <> '\'vitorluis\''
This query would return 1, meaning a record was found and the new data is not unique (fails the unique validation).
If you were to fix the one issue with quoting the value passed to the rule, your query would then end up being:
select count(*) as aggregate from `user` where `username` = 'vitorluis' and `username` <> 'vitorluis'
Obviously, this query would always return 0, so no matter what value you changed the username to, it would always pass the unique rule.
What you're really wanting to do is to make sure that the username you're assigning is unique to every record except for the one record you're currently updating. To do this, you pass to the validation rule the id of the record you're currently updating, so it can create the correct query. Assuming you're updating a record with the id of 10:
select count(*) as aggregate from `user` where `username` = 'vitorluis' and `id_user` <> 10
Edit
edit due to comments
If the id field is notid
, you can specify the id field using the fourth parameter to the unique rule. I have updated the code above to use your id field nameid_user
.
Laravel documentation for the unique rule can be found here.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: npm err! code 1
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.