Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

password reset in laravel 8

Laravel password reset

Today, I will give you an example of “How to reset password in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

laravel password reset send email
send email in laravel to password reset
password reset using Gmail token in laravel

Password Reset in Laravel

Laravel provides it’s own forget password functionality but if you want to create your custom forget password functionality then I will help to create a custom reset password function in PHP laravel. so basically, you can also create custom forget passwords with different models too.

Let’s create a step-by-step custom forgot password in the laravel 8 application.

Update Users Table

$table->string('token')->nullable();
update token field in laravel

Create a Controller

php artisan make:controller AuthUserController

Define Web Routes

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthUserController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/user-login',[AuthUserController::class,'loginform'])->name('user.login');
Route::post('/check-login',[AuthUserController::class,'checklogin'])->name('post.login');

#Password Reset
Route::any('/user-password-reset',[AuthUserController::class,'userpasswordReset'])->name('userpassword.reset');
Route::any('/user/password/reset/update/{token}',[AuthUserController::class,'userpassResetUpdate'])->name('user.resetupdate');

Recommended Article : Custom Login and Signup in Laravel application.

Any Route in Laravel : Use of Any Route in Laravel.

Add SMTP Details in .env File

We will use Gmail SMTP Server to send Emails in Laravel, you can use Mailtrap or other testing SMTP servers.

MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=yoursecurepassword
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=8bityard@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

If you getting any SMTP errors for sending an email please follow this article: Using Gmail SMTP Server to send Email in Laravel.

Create a token and Send Password Reset Link via user email

app\Http\Controllers\AuthUserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use\App\Models\User;
use Auth;
use Crypt;
use Session;
use Illuminate\Support\Facades\Mail;
use App\Mail\UserForgotPassword;
use Illuminate\Support\Facades\Hash;


class AuthUserController extends Controller
{
       public function loginform()
       {
            return view('user.login');
       }

     public function checklogin(Request $request)
       {
          $input = $request->all();
          $this->validate($request, [
              'email' => 'required',
              'password' => 'required'],
              [
              'email.required' => 'Email is required',
              'password.required' => 'Password is required']);

             if(Auth::attempt(['email' => $input['email'], 'password' => $input['password']]))
             {
                Session::put('user_session', $input['email']);
                return redirect('/user-dashboard');
             }
             else
             {
                return redirect('/user-login')->with('error','Invalid credentials');
             }
          }

       public function userpasswordReset(Request $request)
        {
            if($request->isMethod('post')){
            $userData = User::select('id','email')->where('email', '=',$request->email)->first();
            if($userData){
                $token = md5($request->email);
                User::where('email', $request->email)->update(['token' => $token]);
            }
            if(empty( $userData)){
                return redirect()->back()->with('flash_message_error','Email does not exist !');
            }else{
                //mail with link
                Mail::to($request->email)->send(new UserForgotPassword($userData,$token ));
                return redirect()->back()->with('flash_message_success','Password reset Mail Sent Successfully !');
            }

            }else
            {
                return view('user.passwordReset');
            }
        }

        #Password Reset
        public function userpassResetUpdate(Request $request,$token=null)
        {
        if($token){
            if($request->isMethod('post')){

                $validatedData = $request->validate([
                    'new_password' => 'required|min:6',
                    'new_confirm_password' => 'required|min:6|same:new_password',
                    ]);

                $userCredentialupdate = User::where('token',$token)->first();
                if($userCredentialupdate){
                    $userCredentialupdate->token = 'NULL';
                    $userCredentialupdate->password = Hash::make($request->new_confirm_password);
                    $userCredentialupdate->save();
                    return redirect()->route('user.login')->with('flash_message_success','Your Password Reset Successfully! Now you can Login');
                }else{
                    return redirect('/user-login')->with('flash_message_error','Something went wrong!');
                }
                }else
                {
                    return view('user.passwordresetupdate',compact('token'));
                }
            }

        }
}

We will create an email to send forgot password URL and reset the blade File.

php artisan make:mail UserForgotPassword

app\Mail\UserForgotPassword.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class UserForgotPassword extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $user;
    public function __construct($user,$code=null)
    {
        $user['code']= $code;
        $this->user = $user;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
       return $this->view('emails.userforgetpass');
    }
}

Send a Reset Password Link to Email

We will define the routes necessary to actually reset the password once the user clicks on the password reset link that has been emailed to them and provides a new password.

First, let’s define the 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:

resources\views\emails\userforgetpass.php

<body>
Click here the Link :  <a href="{{ URL('/user/password/reset/update/'.$user['code'])}}">Reset Password</a>
</body>
		

resources\viewsuser\login.blade.php

login blade file in laravel with forgot password URL
<main>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h3><a>Password Reset using Gmail in Laravel</a></h3>
                  @if(Session::has('flash_message_error'))
                     <div class="alert alert-sm alert-danger alert-block col-md-8 col-12 offset-4" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="close">
                        <span aria-hidden="true">&times; </span>
                        </button>
                        <strong>{!! session('flash_message_error')!!} </strong>
                     </div>
                     @endif
                     @if(Session::has('flash_message_success'))
                     <div class="alert alert-sm alert-success alert-block col-md-8 col-12 offset-4" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="close">
                        <span aria-hidden="true">&times; </span>
                        </button>
                        <strong>{!! session('flash_message_success')!!} </strong>
                     </div>
                     @endif
                  <form role="form" action="{{route('post.login')}}" method="post">
                     @csrf
                     <div class="form-group">
                        <label for="useremail">Email <span class="text-danger">*</span></label>
                        <input type="email" name="email" class="form-control">
                        @if ($errors->has('email'))
                        <span class="text-danger">{{ $errors->first('email') }}</span>
                        @endif
                     </div>
                     <div class="form-group">
                        <label for="userpassword">Password <span class="text-danger">*</span></label>
                        <input type="password" name="password" class="form-control">
                        @if ($errors->has('password'))
                        <span class="text-danger">{{ $errors->first('password') }}</span>
                        @endif
                     </div>
                     <div class="col-md-3 pl-0 pr-0">
                        <a href="{{route('userpassword.reset')}}" class="float-right remeber-forgot-password">Forgot Password?</a>
                     </div>
                     <button type="submit" class="btn btn btn-secondary">
                     Login
                     </button>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>
  

Recommended Article : Implement Remember me Functionality in Laravel 8?

Action property on the default password reset form

resources\views\user\passwordreset.blade.php

send email to user email in laravel
   <main>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                 <h3><a>Password Reset using Gmail in Laravel</a></h3>
                   
                   @if(Session::has('flash_message_error'))
                     <div class="alert alert-sm alert-danger alert-block col-md-8 col-12 offset-4" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="close">
                        <span aria-hidden="true">&times; </span>
                        </button>
                        <strong>{!! session('flash_message_error')!!} </strong>
                     </div>
                     @endif
                     @if(Session::has('flash_message_success'))
                     <div class="alert alert-sm alert-success alert-block col-md-8 col-12 offset-4" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="close">
                        <span aria-hidden="true">&times; </span>
                        </button>
                        <strong>{!! session('flash_message_success')!!} </strong>
                     </div>
                     @endif

                  <form role="form" action="{{route('userpassword.reset')}}" method="post">
                     @csrf
                     <div class="form-group">
                        <label for="useremail">Email <span class="text-danger">*</span></label>
                        <input type="email" name="email" class="form-control">
                        @if ($errors->has('email'))
                        <span class="text-danger">{{ $errors->first('email') }}</span>
                        @endif
                     </div>
                     <button type="submit" class="btn btn btn-secondary">
                     Submit
                     </button>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>
  

Validating User input Email

check email exist or not in laravel application
$userData = User::select('id','email')->where('email', '=',$request->email)->first();
         if($userData){
            $token = md5($request->email);
               User::where('email', $request->email)->update(['token' => $token]);
            }
            if(empty( $userData)){
                return redirect()->back()->with('flash_message_error','Email does not exist !');
            }else{
                //mail with link
                Mail::to($request->email)->send(new UserForgotPassword($userData,$token ));
            return redirect()->back()->with('flash_message_success','Password reset Mail Sent Successfully  !');
            }

If the User Input email exist

success mail send with reset URL in laravel

Simply, we Store a token in the users table that we use later to verify the password reset request.

update token value in users table in laravel

Update the password

send email in Gmail using smtp in laravel

reset password URL in Gmail in Laravel

resources\views\users/passwordresetupdate.blade.php

reset and update new password in laravel
   <main>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h3><a>Password Reset using Gmail in Laravel</a></h3>
                   @if(Session::has('flash_message_error'))
                     <div class="alert alert-sm alert-danger alert-block col-md-8 col-12 offset-4" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="close">
                        <span aria-hidden="true">&times; </span>
                        </button>
                        <strong>{!! session('flash_message_error')!!} </strong>
                     </div>
                     @endif
                     @if(Session::has('flash_message_success'))
                     <div class="alert alert-sm alert-success alert-block col-md-8 col-12 offset-4" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="close">
                        <span aria-hidden="true">&times; </span>
                        </button>
                        <strong>{!! session('flash_message_success')!!} </strong>
                     </div>
                     @endif
                  <form role="form" action="{{route('user.resetupdate',$token)}}" method="post">
                     @csrf
                     
                     <div class="form-group">
                        <label for="userpassword">New Password <span class="text-danger">*</span></label>
                        <input type="password" name="new_password" class="form-control">
                         @if ($errors->has('new_password'))
                        <span class="text-danger">{{ $errors->first('new_password') }}</span>
                        @endif
                     </div>
                      <div class="form-group">
                        <label for="userpassword">Confirm Password <span class="text-danger">*</span></label>
                        <input type="password" name="new_confirm_password" class="form-control">
                         @if ($errors->has('new_confirm_password'))
                        <span class="text-danger">{{ $errors->first('new_confirm_password') }}</span>
                        @endif
                     </div>
                     <div class="form-group">
                     </div>
                     <button type="submit" class="btn btn btn-secondary">
                     Update
                     </button>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>
  

Recommended Article : The Smart Way To Handle Request Validation In Laravel (Laravel form validation).

forgot password in laravel

Deleting Expired Tokens

$userCredentialupdate->token = 'NULL';
delete token after update password in laravel

Run Application :

127.0.0.1:8000/user-login
password reset using Gmail in laravel

In this article, we learned  “Laravel Custom Forgot & Reset Password Example”, I hope this article will help you with your Laravel application Project.

Also Read: Add Social Media Share Buttons in Laravel 8.