Gammer
Gammer

Reputation: 5608

Laravel validation : Check Exist in two tables

I have the following validation, Where i am trying to check the email in two tables :

$validator = Validator::make($request->all(),
[
    'email' => "exists:users,email|exists:user_company,company_email"
]);

But it only works for one table and that is the users table.

Is there anyway around it ?

Upvotes: 4

Views: 7351

Answers (2)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

try this way :

public function validator(array $data)
{
    $data = ['email2' => $data['email']];

    $rules = [   
        'email' => 'required|email|max:255|unique:users',
        'email2' => 'exists:user_company,company_email',
    ];

    $messages = [
        'email.unique' => 'This email is already exists in users table',
        'email2.exists' => 'This email is already exists in user_company table',
    ];

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

$this->validator($request->all());

Upvotes: 1

Lovepreet Singh
Lovepreet Singh

Reputation: 4840

There is option to add custom validation rules in laravel. Read about this here Laravel Custom Rules

For example:

$validator = Validator::make($request->all(), [
            'email' => ["exists:users,email", function($attribute, $value, $fail) {
                    /* Custom Validation code */
                },],
        ]);

Upvotes: 2

Related Questions