Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating model - email is required to be unique [duplicate]

I have a view that shows a form with pre-populated data related to a user model. This is for updating the model data. When the form is submitted, however, there's a conflict because the email address is not unique (if it hasn't been changed). Yet I still want to be able to store this (or ignore it).

I'm trying to update a model with this controller code:

    $input = Input::all();

    $validator = Validator::make($input, User::$rules['edit']);

    if ($validator->fails()) {
        return Response::json(array(
            'error' => $validator->messages()
        ));
    }

In the model, I've got:

    public static $rules = array(
    'create' => array(
        'email' => 'required|email|unique:users',
        'password' => 'required|confirmed',
        'firstname' => 'required',
        'lastname' => 'required',
        'address_one'=> 'required',
        'postcode'=> 'required'
    ),
    'edit' => array(
        'email' => 'sometimes|required|email|unique:users',
        'password' => 'sometimes|required|confirmed'
    ),
);

But when I update, I get the error message:

"error": {
    "email": [
        "The email has already been taken."
    ]
}

I thought that the sometimes would stop this behaviour. What am I doing wrong?

like image 892
babbaggeii Avatar asked Mar 05 '15 16:03

babbaggeii


1 Answers

You need to specify the user ID so the validator knows it needs to ignore the entry with that ID when checking the entries for uniqueness:

'email' => 'sometimes|required|email|unique:users,' . $id

Taken from the Laravel Docs:

Forcing A Unique Rule To Ignore A Given ID

'email' => 'unique:users,email_address,10'

In your case, since you're keeping the rules in a model property, you'll need to append the ID before passing the rules to the validator. Something like this should do:

$input = Input::all();
$rules = User::$rules['edit'];

// this assumes the user your want to update
// is stored in the $user variable
$rules['email'] .= ',' . $user->id; 

$validator = Validator::make($input, $rules);

if ($validator->fails()) {
    return Response::json(array(
        'error' => $validator->messages()
    ));
}
like image 197
Bogdan Avatar answered Oct 29 '22 12:10

Bogdan