0

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);

Nish Dekardo
  • 329
  • 2
  • 11
  • https://stackoverflow.com/questions/22405762/laravel-update-model-with-unique-validation-rule-for-attribute/22406205 – Tom Nov 13 '20 at 18:16
  • 1
    Does this answer your question? [Laravel update model with unique validation rule for attribute](https://stackoverflow.com/questions/22405762/laravel-update-model-with-unique-validation-rule-for-attribute) – Tom Nov 13 '20 at 18:18

1 Answers1

0

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);
})
STA
  • 30,729
  • 8
  • 45
  • 59
  • @Nish this is an another error, you can solve it by https://laracasts.com/discuss/channels/laravel/constant-expression-contains-invalid-operations-error – STA Nov 13 '20 at 18:41