dmcoding
dmcoding

Reputation: 331

Laravel validation: Unique exception not functioning for one user

My validation rule is...

$rules = [];

    foreach($this->request->get('email') as $key=>$value){
        $rules['email.'.$key] = 'required|regex:/[a-zA-Z]+@[a-zA-Z]+(\.[a-zA-Z]+)+/|unique:admins,admin_email,'.$this->request->get('admin_id')[$key].',admin_id';
    }

Basically, the rule is that it's required, the regex passes, and the email isn't already in use with the exception of if the email is in use by that particular row. However, I'm getting this error message when I run the form:

The email.0 has already been taken.

To be clear, this form has 8 different users and only the first one is giving me this problem. I did a dd() of the rules to see what was different between the validation rules that were being applied, and I didn't see any.

"email.0" => "required|regex:/[a-zA-Z]+@[a-zA-Z]+(\.[a-zA-Z]+)+/|unique:admins,admin_email,0,admin_id"

"email.1" => "required|regex:/[a-zA-Z]+@[a-zA-Z]+(\.[a-zA-Z]+)+/|unique:admins,admin_email,1,admin_id"

"email.2" => "required|regex:/[a-zA-Z]+@[a-zA-Z]+(\.[a-zA-Z]+)+/|unique:admins,admin_email,2,admin_id"

If I update email.0, I don't get this problem. I also don't get this problem with any other rows regardless of whether I update email.0 or not. I can not delete this user as there is a foreign key constraint. To be incredibly clear, the admin_id for this specific admin is 0. Or, in other words, this is how the table looks for this specific entry

admin_id|admin_email
--------+------------
   0    |  [email protected]

Edit: Where does Laravel build and run the actual query? If I can do a dd() on the database log I might be able to find what my problem is (see the actual raw query).

I am obviously missing something here - any help would be greatly appreciated!

Upvotes: 1

Views: 1152

Answers (1)

dbr
dbr

Reputation: 1047

The unique rule shouldn't be as this:

unique:admins,admin_email,0,admin_id

The zero 0 refers to the value of admin_id column which should be ignored by the unique rule.

So if you have table admins as:

admin_id | admin_email
---------+-------------
1        | [email protected]
2        | [email protected]
3        | [email protected]

and you are updating where admin_email == [email protected]

Your rule should look as

unique:admins,admin_email,2,admin_id

Upvotes: 3

Related Questions