0

I want to validate a value that I got from a certain form. The value type is text. I want it to match a specific username from the database from the users table, but also to not match the current user's username.

To achieve that, I used the following validation rules:

'username' => [
    'required',
    'string',
    'exists:App\User,username',
    'different:' . auth()->user()->username
]

What I've discovered is that whenever the auth()->user()->username value includes a digit, it passes the validation even if request()->username = auth()->user()->username. Is there anything I can do to prevent this from happening?

Thanks in advance.

3 Answers 3

4

Use unique like -

Considering id is your user's id.

'username' => 'required|string|unique:username,id,'.auth()->user()->username,

This will check if username is unique or not except this userId.

Sign up to request clarification or add additional context in comments.

11 Comments

I'm afraid this won't work for me. I want it to refer to an existing record in the database, which unique doesn't support.
unique will consider in exsting records as well. refer - laravel.com/docs/7.x/validation
What do you mean? I am not getting you. Can your elaborate, please?
|
2

The answer to this issue was creating own Rule::exists validation, which is shown below:

'username' => [
    'required',
    'string',
    Rule::exists('users')->where(function ($query) {
        $query->where('username', '<>', auth()->user()->username);
    })
],

Comments

1

I solved a similar problem as follows.

$request->validate([
            'email' => ['required', 'email','unique:users,email,'.Auth::id()],
            'phone' => ['required', 'unique:users,phone,'.Auth::id()],
        ]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.