Forgot Password Vue Laravel

User
create forget password vue js laravel standalone
Assistant
Here’s a step-by-step guide to creating a **standalone "Forgot Password" feature in Vue.js with Laravel as the backend**:

### **Backend (Laravel)**
1. **Set Up Routes (`routes/api.php`)**

use IlluminateSupportFacadesRoute;
   use AppHttpControllersAuthForgotPasswordController;

   Route::post('/forgot-password', [ForgotPasswordController::class, 'sendResetLink']);
   Route::post('/reset-password', [ForgotPasswordController::class, 'resetPassword']);

2. **Create Controller (`app/Http/Controllers/Auth/ForgotPasswordController.php`)**

namespace AppHttpControllersAuth;

   use AppHttpControllersController;
   use IlluminateHttpRequest;
   use IlluminateSupportFacadesPassword;
   use IlluminateSupportFacadesHash;
   use IlluminateSupportFacadesValidator;
   use AppModelsUser;

   class ForgotPasswordController extends Controller
   {
       public function sendResetLink(Request $request)
       {
           $request->validate(['email' => 'required|email|exists:users,email']);

           $status = Password::sendResetLink($request->only('email'));

           return $status === Password::RESET_LINK_SENT
               ? response()->json(['message' => __($status)], 200)
               : response()->json(['error' => __($status)], 400);
       }

       public function resetPassword(Request $request)
       {
           $request->validate([
               'email' => 'required|email|exists:users,email',
               'token' => 'required',
               'password' => 'required|string|min:6|confirmed',
           ]);

           $status = Password::reset(
               $request->only('email', 'password', 'password_confirmation', 'token'),
               function ($user, $password) {
                   $user->forceFill([
                       'password' => Hash::make($password),
                   ])->save();
               }
           );

           return $status === Password::PASSWORD_RESET
               ? response()->json(['message' => __($status)], 200)
               : response()->json(['error' => __($status)], 400);
       }
   }

3. **Set Up Email Configuration**
In `.env`:

MAIL_MAILER=smtp
   MAIL_HOST=smtp.mailtrap.io
   MAIL_PORT=2525
   MAIL_USERNAME=your_mailtrap_username
   MAIL_PASSWORD=your_mailtrap_password
   MAIL_ENCRYPTION=tls
   MAIL_FROM_ADDRESS=no-reply@example.com
   MAIL_FROM_NAME="Your App"

4. **Run Migrations (Ensure Password Resets Table Exists)**

php artisan migrate

### **Frontend (Vue.js)**
1. **Set Up Axios in `main.js` (if not already set)**

import axios from 'axios';
   axios.defaults.baseURL = 'http://localhost:8000/api';

2. **Forgot Password Component (`ForgotPassword.vue`)**

<template>
     <div>
       <h2>Forgot Password</h2>
       <form @submit.prevent="sendResetLink">
         <input type="email" v-model="email" placeholder="Enter your email" required />
         <button type="submit">Send Reset Link</button>
       </form>
       <p v-if="message">{{ message }}</p>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         email: '',
         message: ''
       };
     },
     methods: {
       async sendResetLink() {
         try {
           const response = await axios.post('/forgot-password', { email: this.email });
           this.message = response.data.message;
         } catch (error) {
           this.message = error.response.data.error;
         }
       }
     }
   };
   </script>

3. **Reset Password Component (`ResetPassword.vue`)**

<template>
     <div>
       <h2>Reset Password</h2>
       <form @submit.prevent="resetPassword">
         <input type="email" v-model="email" placeholder="Enter your email" required />
         <input type="text" v-model="token" placeholder="Enter token" required />
         <input type="password" v-model="password" placeholder="New Password" required />
         <input type="password" v-model="password_confirmation" placeholder="Confirm Password" required />
         <button type="submit">Reset Password</button>
       </form>
       <p v-if="message">{{ message }}</p>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         email: '',
         token: '',
         password: '',
         password_confirmation: '',
         message: ''
       };
     },
     methods: {
       async resetPassword() {
         try {
           const response = await axios.post('/reset-password', {
             email: this.email,
             token: this.token,
             password: this.password,
             password_confirmation: this.password_confirmation
           });
           this.message = response.data.message;
         } catch (error) {
           this.message = error.response.data.error;
         }
       }
     }
   };
   </script>

### **Final Steps**
– Ensure Laravel's queue worker is running for email dispatch:

php artisan queue:work

– Test the flow:
1. Enter an email in the "Forgot Password" form.
2. Check the email for a reset link/token.
3. Use the "Reset Password" form to change the password.

Now you have a **fully functional standalone password reset system with Vue.js and Laravel**! 🚀 Let me know if you need improvements.

User
sendResetLink what the link will be
Assistant
In the `sendResetLink` method of `ForgotPasswordController`, Laravel's `Password::sendResetLink()` function automatically generates a **password reset token** and emails it to the user.

By default, Laravel uses the built-in `PasswordResetNotification`, which sends an email with a link formatted as:

https://yourfrontend.com/reset-password?token=xxx&email=user@example.com

### **How to Customize the Reset Link?**
If you want to customize the link, you can override Laravel's default notification.

#### **Step 1: Create a Custom Notification**
Run the following command:

php artisan make:notification ResetPasswordNotification

This creates a new file in:
`app/Notifications/ResetPasswordNotification.php`

#### **Step 2: Modify the Notification File**
Edit `app/Notifications/ResetPasswordNotification.php` and modify the `toMail` method:

namespace AppNotifications;

use IlluminateNotificationsNotification;
use IlluminateNotificationsMessagesMailMessage;
use IlluminateAuthNotificationsResetPassword as ResetPasswordBase;

class ResetPasswordNotification extends ResetPasswordBase
{
    public function toMail($notifiable)
    {
        $frontendUrl = env('FRONTEND_URL', 'http://localhost:3000'); // Change this to your Vue app URL
        $resetLink = "{$frontendUrl}/reset-password?token={$this->token}&email={$notifiable->email}";

        return (new MailMessage)
            ->subject('Reset Your Password')
            ->line('Click the button below to reset your password:')
            ->action('Reset Password', $resetLink)
            ->line('If you did not request a password reset, no further action is required.');
    }
}

#### **Step 3: Use the Custom Notification in Your Model**
Update your `User` model (`app/Models/User.php`):

use AppNotificationsResetPasswordNotification;

public function sendPasswordResetNotification($token)
{
    $this->notify(new ResetPasswordNotification($token));
}

#### **Step 4: Update Your `.env` File**

FRONTEND_URL=http://yourfrontend.com

### **Final Reset Link**
After implementing the above changes, the user will receive an email with a reset link like:

https://yourfrontend.com/reset-password?token=abcdef123&email=user@example.com

Your Vue.js frontend can then use these parameters to verify and process the password reset request. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *