How To

How to Change Password with Current Password in Laravel 8

Hello Laravel Friends,

In today’s blog, we will learn about How to Change Password with Current Password in Laravel 8.

Security is the main concern for websites. Passwords protect our data but they must be frequently changed to avoid any data breach. Laravel provides default Change Password functionality.

Let’s check How to Change Password with Current Password in Laravel 8.

Prerequisites

Before we start, we need some prerequisites that are followed here.

  1. A Laravel Project.
  2. You have a basic idea of the login or authentication flow of Laravel

Perform Laravel Authentication with Breeze

Steps to Change Password with Current Password in Laravel 8:

Step 1: First you need to create a View File named change-password.blade.php at the below path

resources/views/user/change-password.blade.php

Then add the code as follows

<!DOCTYPE html>
<html>

<head>
    <title>Change Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>

<body>
    <div class="container-fluid">
        <div class="col-md-6 offset-3 pt-4">
            <h3 class="text-center">Change Password</h3>
            @if($errors->any())
            {!! implode('', $errors->all('<div style="color:red">:message</div>')) !!}
            @endif
            @if(Session::get('error') && Session::get('error') != null)
            <div style="color:red">{{ Session::get('error') }}</div>
            @php
            Session::put('error', null)
            @endphp
            @endif
            @if(Session::get('success') && Session::get('success') != null)
            <div style="color:green">{{ Session::get('success') }}</div>
            @php
            Session::put('success', null)
            @endphp
            @endif
            <form class="form" action="{{ route('postChangePassword') }}" method="post">
                @csrf
                <div class="mb-3">
                    <label for="current_password" class="form-label">Current Password</label>
                    <input type="password" class="form-control" id="current_password" name="current_password">
                </div>
                <div class="mb-3">
                    <label for="new_password" class="form-label">New Password</label>
                    <input type="password" class="form-control" id="new_password" name="new_password">
                </div>
                <div class="mb-3">
                    <label for="new_password_confirmation" class="form-label">Confirm New Password</label>
                    <input type="password" class="form-control" id="new_password_confirmation" name="new_password_confirmation">
                </div>
                <button type="submit" class="btn btn-primary text-center">Submit</button>
            </form>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
</body>

</html>

Step 2: Now create UserController at the below path

app/Http/Controller/UserController.php

Also create supporting controller method

  1. changePassword function used for load view page
  2. changePasswordSave function is used for saving the new password and performing their validation.

Add the code as follows

<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    public function changePassword(Request $request)
    {
        return view('users.change-password');
    }

    public function changePasswordSave(Request $request)
    {
        
        $this->validate($request, [
            'current_password' => 'required|string',
            'new_password' => 'required|confirmed|min:8|string'
        ]);
        $auth = Auth::user();

 // The passwords matches
        if (!Hash::check($request->get('current_password'), $auth->password)) 
        {
            return back()->with('error', "Current Password is Invalid");
        }

// Current password and new password same
        if (strcmp($request->get('current_password'), $request->new_password) == 0) 
        {
            return redirect()->back()->with("error", "New Password cannot be same as your current password.");
        }

        $user =  User::find($auth->id);
        $user->password =  Hash::make($request->new_password);
        $user->save();
        return back()->with('success', "Password Changed Successfully");
    }
}

Step 3: Add the below code to your route file

use App\Http\Controllers\UserController;
Route::group(['middleware' => 'auth'], function ()
{
    Route::get('/change-password', [UserController::class, 'changePassword'])->name('changePassword');
    Route::post('/change-password', [UserController::class, 'changePasswordSave'])->name('postChangePassword');
});

Now let’s test the result

Open {{YOUR HOST}}/change-password URL in your browser.

This will open a change password screen as follows

If the new password is less than 8 characters, it will show the following error

If the current password is incorrect, it will show the following error

If the new password and confirm password do not match, it will show the following error

If everything is entered correctly, the password gets successfully changed

Conclusion:

This way you can Change Password with Current Password in Laravel 8. If you have any doubt let me know through the comments box. Share the tutorial with your friends and stay in touch with us for more Laravel tutorials.

Happy Coding!

Click to rate this post!
[Total: 9 Average: 4.3]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ? with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket ?.

View Comments

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

5 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago