1

I have a noodle scratcher that I can't seem to figure out. I am validating for unique usernames and emails addresses. I have the following rules:

protected $rules = array(
    'username' => 'required|min:4|unique:users,username',
    'email'    => 'email|unique:users,email',
    'password' => 'min:6',
);

If I update a form that has the username (which is the same as it currently is), I get a The username has already been taken. error. If I do the same with the email, I get no error at all.

I know about adding the last param to the unique validation:

'unique:users,username,{{$id}}' or 'unique:users,username,'.$id

This doesn't work on the username. I get the same issue.

I can't figure out why this works for the email, but not the username.

Anyone had a similar issue or know where I am going wrong?

Many thanks,

T2theC
  • 542
  • 3
  • 10
  • 23

2 Answers2

1

this is my code, i use laravel 8

$this->validate($request, [
    'name'      => ['required', 'string', 'max:255'],
    'email'     => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$user->id],
    'username'  => ['string', 'max:255',"unique:users,username,{$user->id}"],
    'roles'  => ['required'],
]);
Riki krismawan
  • 503
  • 1
  • 3
  • 10
0

The most likely reason is because $id is probably being pulled in through your URI, so it is not part of Input::all().

To have it validated you would need to either include a hidden "id" field in your form or request, OR you would need to extend your repository or controller with a validate method which adds id back into the array of data being validated.

/**
 * Validate
 *
 * @param $data
 * @param $id
 * @throws \ValidationException
 * @return boolean
 */
public function validate($data, $id = null)
{
    $rules = SomeModel::$rules;
    if(! is_null($id))
    {
       $data['id'] = $id;
       // Only add exclude rule to end of rule if you haven't included already
       $rules['username'] .= ',' . $data['id'];
    }
    $validator = \Validator::make($data, $rules);
    if($validator->fails()) {
        throw new \ValidationException($validator);
    }
    return TRUE;
}

Note: The ValidationException is not a normal exception, so either create this exception type or modify code to handle validation errors.

BayssMekanique
  • 894
  • 1
  • 14
  • 27