Search code examples
phplaravellaravel-validation

Form validator unique username fails


I'm having difficulties detecting a unique username. I mean it does work to detect username but I would like to exclude the username validation if the request input username matches with that users current username in database.

Currently, I'm getting: The username has already been taken. despite the fact the its the same username as the one this user has in the database.

Thank you!

Rules

    protected $rules = [
        'username'  => 
 'nullable|string|alpha_dash|max:255|regex:/(^([a-zA-Z]+)(\d+)?$)/u|unique:users',
        'first_name' => 'nullable|max:150',
     'last_name' => 'nullable|max:150', 
      'location' => 'nullable|max:200', 
      'password' => 'confirmed'
    ];

Edit Profile POST method:


$validator = Validator::make($request->all(), $this->rules);

        if ($validator->fails()) {
            return \redirect()->back()->withErrors($validator->getMessageBag()->toArray())->withInput($request->except('image'));
        } else {
            $model = \App\User::find(\Auth::user()->id);


Solution

  • On update you can ignore the field as :

    'username'  => 
     'nullable|string|alpha_dash|max:255|regex:/(^([a-zA-Z]+)(\d+)?$)/u|unique:users,' . $user->id,
    

    Or,

    'username' => [
       'nullable',
       'string',
       Rule::unique('users')->ignore($user->id),
    ],
    

    You may pass a different column name as the second argument to the unique method:

    Rule::unique('users', 'username')->ignore($user->id),
    

    You may also specify additional query constraints by customizing the query using the where method. For example :

    Rule::unique('users')->where(function ($query) {
        return $query->where('username', '!=',  $request->username);
    })