Welcome Guest, Not a member yet? Register   Sign In
Form validation is_unique: valid if value is in current row, invalid on any other row

(This post was last modified: 05-09-2021, 05:32 AM by BFlokstra. Edit Reason: Solved it myself )

I have a form where I edit customer information. There are two fields that have to be unique:
- organisatie_naam,
- contactpersoon_email

When inserting the customer the is_unique validation works perfectly. If the organisatie_naam or contactpersoon_email already exists in the table I get the appropriate validation error. Now I want to do the same when updating the customer. As you can imagine, the customers name (is a company name) doesn't change that often while the postal address of contact person can change on occasion. 
I use the same form to update all customer information at the same time. 

Is there a way to use the is_unique validation to check if the field organisatie_naam is unique while ignoring the row it is in? 

What am I experiencing now?
Right now when I do not change the customer name but do change (for example) the postal address I get a validation error: "The organisatie_naam field must contain a unique value."
This is understandable. That name is already in the database. But how do I make the validation ignore the row this specific customer is in, to that the validation checks if the customer name is nog present in any of the OTHER rows and therefore unique in this context.

As you can see I added the id to the is_unique validation hoping this would do what I want, but no luck.

PHP Code:
$rules = [
                'organisatie_naam' => 'required|alpha_numeric_punct|min_length[4]|is_unique[organisaties.organisatie_naam,organisaties.id]',

Okay, I solved it myself. I hate it when I'm facing a problem, find a forum post with the exact problem I'm having and the OP says "I sloved it" without showing how he did it. So here is my solution:

It turns out that in the validation rule you have to not only pass the column name that where the rule has to look for the rown to be ignored. You also need to pass the exact value that needs to be ignored. So I changes this:
'organisatie_naam' => 'required|alpha_numeric_punct|min_length[4]|is_unique[organisaties.organisatie_naam,organisaties.id]',

to this:
'organisatie_naam' => 'required|alpha_numeric_punct|min_length[4]|is_unique[organisaties.organisatie_naam,organisaties.id,' . $id.']',

Messages In This Thread
Form validation is_unique: valid if value is in current row, invalid on any other row - by BFlokstra - 05-09-2021, 05:10 AM

Theme © iAndrew 2016 - Forum software by © MyBB