Change Password with Current Password Laravel

Change Password with Current Password Laravel

 Change Password with Current Password Validation in Laravel App

In this tutorial, we will create an example from starch. First, we will create Auth then we create a change password page. After that, we will create our custom validation rules for checking the current password on the database. Then we use those custom validation rules on our controller file.

So, you need to just follow a few steps to get a complete guide for validating old passwords using custom validation in Laravel. You can see bellow attach a screenshot of the layout of our example:

Step 1: Install Laravel 

first of all, we need to get a fresh Laravel  version application using the bellow command, So open your terminal OR command prompt and run the bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Create a Custom Validation Rule

After you can set up migration and basic Auth. I didn’t write here for run migration and basic Auth because you know how to do that. now we need to create new validation rules using the following command:

php artisan make:rule MatchOldPassword

After this, we can see they created a new “Rules” folder with one file in the app directory. you can update that file this way:

app/Rules/MatchOldPassword.php

<?php
  
namespace App\Rules;
  
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Hash;
  
class MatchOldPassword implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return Hash::check($value, auth()->user()->password);
    }
   
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute is match with old password.';
    }
}

Step 3: Create Routes

Here, we need to add two routes for view and another for post route. so open your “routes/web.php” file and add the following route.

routes/web.php

Route::get('change-password', 'ChangePasswordController@index');
Route::post('change-password', 'ChangePasswordController@store')->name('change.password');

Step 4: Create a New Controller

In this step, now we should create a new controller as ChangePasswordController. In this file, we will create two methods index() and store(). we will also use validation here. so let’s do it.

app/Http/Controllers/ChangePasswordController.php

<?php
   
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Rules\MatchOldPassword;
use Illuminate\Support\Facades\Hash;
use App\User;
  
class ChangePasswordController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
   
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('changePassword');
    } 
   
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function store(Request $request)
    {
        $request->validate([
            'current_password' => ['required', new MatchOldPassword],
            'new_password' => ['required'],
            'new_confirm_password' => ['same:new_password'],
        ]);
   
        User::find(auth()->user()->id)->update(['password'=> Hash::make($request->new_password)]);
   
        dd('Password change successfully.');
    }
}

Step 5: Create Blade File

In this step, we need to create a changePassword blade file and we will write code for form creation and display error messages. so let’s create the file and put the bellow code:

resources/views/changePassword.blade.php

@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">Laravel - Change Password with Current Password Validation Example - ItSolutionStuff.com</div>
   
                <div class="card-body">
                    <form method="POST" action="{{ route('change.password') }}">
                        @csrf 
   
                         @foreach ($errors->all() as $error)
                            <p class="text-danger">{{ $error }}</p>
                         @endforeach 
  
                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">Current Password</label>
  
                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="current_password" autocomplete="current-password">
                            </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="new_password" type="password" class="form-control" name="new_password" autocomplete="current-password">
                            </div>
                        </div>
  
                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">New Confirm Password</label>
    
                            <div class="col-md-6">
                                <input id="new_confirm_password" type="password" class="form-control" name="new_confirm_password" autocomplete="current-password">
                            </div>
                        </div>
   
                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    Update Password
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now we are ready to run our example so run the below command so quick run:

php artisan serve

Now you can open the URL on your browser:

http://localhost:8000/ 
Reactions

Post a Comment

0 Comments

close