1
1
10013602020-07-29 09:28:00
Laravel
1001360, 2020-07-29 09:28:00

Laravel: How to check 2 fields for uniqueness when registering a user?

How to check 2 fields for uniqueness when registering a user?

The registration form contains 2 main unique fields (Phone number and email)

In the controller file

App\Http\Controllers\Auth\RegisterController.php


I create this structure

protected function validator(array $data){

        $messages = [
            'email.unique'    => 'Данный email зарегестрирован',
            'phone.unique'    => 'Данный номер телефона зарегестрирован',
            'required' => 'Поле объязательно для заполнения',
            'accepted' => 'Вы не приняли условия соглашения',
        ];

        $phone = $data['phone'];
        $email = $data['email'];
        
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'surname' => ['required', 'string', 'max:255'],
            'phone' => [
                'required',
                Rule::unique('users')->where(function ($query) use($phone,$email) {
                    return $query->where('phone', $phone)
                    ->where('email', $email);
                }),
                // Rule::unique('users')->ignore($user->id),
            ],
            // 'phone' => ['required', 'string', 'max:255', 'unique:users'],
            'email' => ['required', 'string', 'email', 'max:255'],
            'password' => ['required', 'string', 'confirmed'],
            'checkbox' => ['accepted'],
        ];

        return Validator::make($data, $rules, $messages);

    }


Tell me what the problem is, I get an error that this user is already in the database

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '89008007060' for key 'users_phone_unique'


Just in case, I’ll say that these 2 fields are unique in the database, I created them through the migration file like this:

$table->string('phone')->unique();
$table->string('email')->unique();


I will also add that there is already a user in the database whose I am trying to register again, but at the same time I want to get errors in the form, just like in the standard, the unique email field gives an error

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-07-29
@jazzus

https://laravel.com/docs/7.x/validation#rule-unique

'phone' => 'unique:users'
'email' => 'unique:users'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question