skip to Main Content

I’m doing the forgot password and recover password feature using Laravel API and React. I’ve done the form and now I’m stuck at the backend part.

In the forgotPassword function, it will send a link for recover password at the user’s email. But this code Mail::send('email.forgetPassword', is a view file for Laravel. How to adjust this part for React? This is my first time doing auth using Laravel hehe.

Function

public function forgotPassword(Request $request){
        $request->validate(['email' => ['required', 'string', 'email', 'max:255']]);

        $token = Str::random(64);

        DB::table('password_reset_tokens')->insert([
            'email' => $request->email,
            'token' => $token,
            'created_at' => Carbon::now()
        ]);

        Mail::send('email.forgetPassword', ['token' => $token], 
            function($message) use ($request){
                $message->to($request->email);
                $message->subject('Reset Password');
            }
        );

        return response()->json(['message', 'We have e-mailed your password reset link!']);
    }

Route

Route::post('forgot-password', [UserController::class, 'forgotPassword'])->name('password.email');

Forgot Password Form

const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);
    setStatus(null);

    const data = {email};
 
    try {
      await API.get("/api/csrf-cookie").then(async () => {           
        const response = await API.post('/api/forgot-password', data); 
        setStatus(response.data.status);
        if (response.data.error){
          console.log(response.data.error);
          setLoading(false);             
        }
      });          
    } catch (error){
      console.log(error);
      setLoading(false);
    }
}

2

Answers


  1. I can see that in your question you’re doing the process manually, while Laravel provides built-in services that you can use to implement this functionality robustly and easily.

    Let’s take a brief look at the process:

    1. Prepare your authenticatable model(s): your authenticatable model(s) (e.g. AppModelsUser, or any other model that has login capabilities) must implement the IlluminateContractsAuthCanResetPassword interface, and it should use the IlluminateAuthPasswordsCanResetPassword trait.

    2. Prepare your routes: your application must contain 4 basic routes, these routes are as follows:

      1. password.request: A GET route that returns the view that contains a form in which the user will be asked to enter his E-mail. Since you’re using React, you don’t need to return any view, so you can leave this route empty, but you must define it nevertheless.
      2. password.email: A POST route that handles the form submission request, this route will be responsible for validating the email address and sending the password reset request to the corresponding user. Here, sending the reset password link to the user is as easy as calling the IlluminateSupportFacadesPassword::sendResetLink() method.
      3. password.reset: A GET route that will display the reset password form that is displayed when the user clicks the reset password link. This route will receive a token parameter that we will use later to verify the password reset request. Once again, since you’re using React, you may leave this route empty, but it must be defined whatsoever.
      4. password.update: A POST route that will be responsible for validating the incoming request and updating the user’s password in the database.

    Notice that you don’t need to interact with the password_reset_tokens table, Laravel does that automatically.

    Regarding your question about the mail template: this is a blade file that gets turned into an E-mail and sent over to the user. In order to do customizations on this template, you should run the command:

    php artisan vendor:publish --tag=laravel-mail
    
    

    Which will create a new resources/views/vendor/mail directory that contains the template files for the mail.

    You can learn more about Laravel password reset functionality at: https://laravel.com/docs/10.x/passwords

    Login or Signup to reply.
  2. php artisan vendor:publish –tag=laravel-mail

    Which will create a new resources/views/vendor/mail directory that contains the template files for the mail.

    You can learn more about Laravel password reset functionality at: https://laravel.com/docs/10.x/passwords

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search