1

I have contacts table with field email and alteranate_email. While adding new contact i want to check email address should not present in either email or alteranate_email. For Example, There is contact present with alteranate_email = '[email protected]'. When I tried to add new contact with email = '[email protected]', it allows me to add new contact.

I have tried below code but its not working.

 $validator = Validator::make($request->all(), [
            'email' => ['nullable', 'email',
                 Rule::unique('contacts')->where(function ($query) use ($request) {
                     return $query->where('email', $request->email)->orWhere('alteranate_email', $request->email);
                 }),
            ],

        ]);
6
  • 'email' => 'nullable|email|unique: contacts.email,alteranate_email' Commented Mar 27, 2020 at 7:53
  • no it doesnt work Commented Mar 27, 2020 at 7:57
  • why it is not working? what error do you get? Commented Mar 27, 2020 at 8:14
  • it allows me to add new contact even if email address present in alternate email address field. Commented Mar 27, 2020 at 8:27
  • remove whitespace between unique: and contacts - 'email' => 'nullable|email|unique:contacts.email,alteranate_email' Commented Mar 27, 2020 at 8:39

1 Answer 1

1

You try to use two unique instead of making new rule. Try these one line solution below.

'email' => 'nullable|email|unique:contacts,email|unique:contacts,alternate_email'
Sign up to request clarification or add additional context in comments.

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.