Faisal Shani
Faisal Shani

Reputation: 810

Check uniqueness of two columns in two tables using validator in Laravel

I am taking input of a field named "email", and checking it using laravel validator. The problem is I want to make sure that the "email" data should be unique in two columns in two different tables. (Sellers and Buyers must not have the same email in their "email" column).

I am able to check the input from one table and column, How should I check the input in both columns? Below is my code.

    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'emailOrNumber' => ['required', 'string','email','max:255','unique:usersNew,email'],
        'password' => ['required', 'string', 'min:8'],

         ]);

The above code check email only in usersNew table and in email column, How can I check both tables in here?

Upvotes: 1

Views: 1525

Answers (4)

lagbox
lagbox

Reputation: 50491

You can use the unique rule twice. Once for each table you need to check a field for uniqueness:

'email' => [..., 'unique:table1', 'unique:table2'],

When you don't pass a column to the unique rule it will use the current field name being validated, email in this example.

Laravel 6.x Docs - Validation - Rules - unique

Upvotes: 3

user10678889
user10678889

Reputation:

Try this one,

return Validator::make($data, [
    'email' => ['required',     'string','email','max:255','unique:user|unique:email'],
    'password' => ['required', 'string', 'min:9'],

     ]);

In this code unique:username|unique:email will assume the email and username as unique

Upvotes: 1

Maxim Abdalov
Maxim Abdalov

Reputation: 559

just use it

'email' => 'unique:table1,your_column_name|unique:table2:your_column_name_2'

or use it answer https://laracasts.com/discuss/channels/laravel/validate-a-field-from-2-tables-with-different-message

Upvotes: 1

Vikas Verma
Vikas Verma

Reputation: 149

use below code

 return Validator::make($data, [
    'name' => ['required', 'string', 'max:255'],
    'emailOrNumber' => ['required',     'string','email','max:255','unique:usersNew|unique:email'],
    'password' => ['required', 'string', 'min:8'],

     ]);

Hope it will help you

Upvotes: 0

Related Questions