2

I have a form with an update user email.

Controller

public function update_email(Request $request, User $user)
{
    $request->validate([
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
    ]);

    // code to verify that new email address exists
    $userUpdate = User::where('id', $user->id)
        ->update([
            'email' => $request->input('email'),
        ]);

    if ($userUpdate) {
        return redirect()
            ->back()
            ->with('success', 'Email updated successfully');
    }

    return back()->withInput();
}

This method verifies email according to standards and updates it in the database. However, I can't verify that the email actually exists.

How can I verify the provided new email? One thing I saw in previous posts is to use the inbuilt VerifiesEmails trait for Laravel. However, I don't understand the explanation provided for them. Is there any way to use it for this purpose?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
ahrooran
  • 931
  • 1
  • 10
  • 25

1 Answers1

1

Try this.

'email' => 'required|unique:users,email,'.$user->id

or

'email' => 'required|email|unique:users,email,'.$this->user

public function update_email(Request $request, User $user)
    {
        $rules = array(
            'email' => 'required|unique:users,email,'.$user->id
        );
        $validator = Validator::make($input, $rules);
        if ($validator->fails()) {
            $arr = array("status" => 400, "message" => $validator->errors()->first(), "data" => array());
        }

        // code to verify that new email address exists

        $userUpdate = User::where('id', $user->id)
            ->update([
                'email' => $request->input('email'),
            ]);

        if ($userUpdate) {
            return redirect()
                ->back()
                ->with('success', 'Email updated successfully');
        }
        return back()->withInput();
    }
VIKAS KATARIYA
  • 5,867
  • 3
  • 17
  • 34