Share this:

In today tutorial we are going to learn Laravel 10 Custom Forgot Password Example. Laravel is a popular PHP framework that makes web development more efficient and enjoyable.

One essential feature of any modern application is a secure and user-friendly password reset mechanism. In this tutorial, we will create a custom forgot password example using Laravel 10.

We will cover the following steps in this tutorial:

  1. Setting up a new Laravel project
  2. Creating and configuring a custom password reset controller
  3. Creating views for password reset
  4. Defining routes for password reset
  5. Testing the forgot password functionality

Let’s get started!

Step 1: Setting up a New Laravel Project

Before we begin, ensure that you have Laravel installed on your system. If you haven’t installed it yet, visit the official Laravel documentation to learn how to install the Laravel installer: https://laravel.com/docs/10.x/installation

Once Laravel is installed, open your terminal and run the following command to create a new Laravel project:

laravel new custom-forgot-password

Now, navigate to the project directory:

cd custom-forgot-password

Next, install the required dependencies by running:

composer install

Finally, set up your .env file with the appropriate database and mail configuration.

Step 2: Creating and Configuring a Custom Password Reset Controller

In this step, we will create a custom password reset controller to handle the password reset logic.

First, generate a new controller using the following command:

php artisan make:controller CustomForgotPasswordController

Now, open the newly created file app/Http/Controllers/CustomForgotPasswordController.php and add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;

class CustomForgotPasswordController extends Controller
{
    public function forgotPassword(Request $request)
    {
        $request->validate([
            'email' => 'required|email'
        ]);

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

        if ($status == Password::RESET_LINK_SENT) {
            return back()->with(['status' => __($status)]);
        }

        return back()->withErrors(['email' => __($status)]);
    }

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

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

        if ($status == Password::PASSWORD_RESET) {
            return redirect()->route('login')->with('status', __($status));
        }

        return back()->withErrors(['email' => [__($status)]]);
    }
}

In the code above, we have two methods: forgotPassword() and resetPassword(). The forgotPassword() method validates the email address and sends a password reset link to the user’s email. The resetPassword() method takes the token, email, and new password as inputs, validates them, and resets the user’s password.

Step 3: Creating Views for Password Reset

In this step, we will create the necessary views for the password reset functionality.

First, create a new directory resources/views/auth to store our authentication-related views.

Next, create a new file resources/views/auth/forgot-password.blade.php for the forgot password view and add the following code:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Forgot Password') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('password.email') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Email Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Send Password Reset Link') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, create another file resources/views/auth/reset-password.blade.php for the reset password view and add the following code:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Reset Password') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('password.update') }}">
                        @csrf

                        <input type="hidden" name="token" value="{{ $token }}">

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Email Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('New Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required>

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm New Password') }}</label>

                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
                            </div>
                        </div>
                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Reset Password') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

These two views handle the user interface for the forgot password and password reset functionality.

Step 4: Defining Routes for Password Reset

Now, we need to define the routes for our custom password reset controller. Open the routes/web.php file and add the following code:

use App\Http\Controllers\CustomForgotPasswordController;

Route::get('/forgot-password', function () {
    return view('auth.forgot-password');
})->middleware('guest')->name('password.request');

Route::post('/forgot-password', [CustomForgotPasswordController::class, 'forgotPassword'])
    ->middleware('guest')
    ->name('password.email');

Route::get('/reset-password/{token}', function ($token) {
    return view('auth.reset-password', ['token' => $token]);
})->middleware('guest')->name('password.reset');

Route::post('/reset-password', [CustomForgotPasswordController::class, 'resetPassword'])
    ->middleware('guest')
    ->name('password.update');

We have defined four routes:

  1. A GET route to display the forgot password form.
  2. A POST route to submit the forgot password form and send the reset link.
  3. A GET route to display the password reset form.
  4. A POST route to submit the password reset form and update the user’s password.

Step 5: Testing the Forgot Password Functionality

Now that we have our custom password reset functionality set up, it’s time to test it. Start the Laravel development server with the following command:

php artisan serve

Navigate to http://127.0.0.1:8000/forgot-password in your web browser. Enter your email address and submit the form. You should receive an email containing the password reset link.

Click on the link in the email and reset your password by entering a new one. After resetting your password, you should be redirected to the login page with a confirmation message.

Conclusion

In this tutorial, we have demonstrated how to create a custom forgot password functionality using Laravel 10. By following these steps, you can easily implement a secure and user-friendly password reset process in your Laravel applications. Happy coding!

Share this:

Categorized in: