Compare Password Inputs in Laravel Validation

Posted on

Explanation of the confirmed Validation Rule

This article will guide you through the complete process of Compare Password Inputs in Laravel Validation. In Laravel, the confirmed validation rule automatically checks if the password_confirmation field matches the password field, so you don’t need to explicitly define password_confirmation in the validation rules.

The confirmed validation rule ensures that the password field matches the password_confirmation field. When you apply this rule, Laravel will look for an input field named password_confirmation and compare its value to the password field.

Validation Rule: The password field must be filled, have a minimum length of 8 characters, and must match the password_confirmation field. The confirmed rule will look for an input named password_confirmation to perform the comparison.

What Happens When password and password_confirmation Do Not Match?

If the password and password_confirmation fields do not match, Laravel will automatically return the user to the form with an error message indicating that the passwords do not match. This error message is generated by Laravel’s validation system and can be easily displayed in your form using Blade templating.

Step-by-Step Guide

Step 1: Create the HTML Form

Ensure your form includes @csrf for security and that both password and password_confirmation fields are present.

<form class="form-horizontal" action="/updateprofile" method="post">
    @csrf
    <div class="form-group mb-3">
        <div class="row">
            <div class="col-md-3"><label class="form-label">Password</label></div>
            <div class="col-md-9">
                <input type="password" name="password" class="form-control" placeholder="Password" required>
                @if ($errors->has('password'))
                    <span class="text-danger">{{ $errors->first('password') }}</span>
                @endif
            </div>
        </div>
    </div>

    <div class="form-group mb-3">
        <div class="row">
            <div class="col-md-3"><label class="form-label">Confirm Password</label></div>
            <div class="col-md-9">
                <input type="password" name="password_confirmation" class="form-control" placeholder="Confirm Password" required>
                @if ($errors->has('password_confirmation'))
                    <span class="text-danger">{{ $errors->first('password_confirmation') }}</span>
                @endif
            </div>
        </div>
    </div>

    <div class="card-footer">
        <button type="submit" class="btn btn-primary waves-effect waves-light">Update Profile</button>
    </div>
</form>

Step 2: Handle Validation in the Controller

Add validation logic in your controller to check if the new password matches the confirmation password, and verify if the new password is different from the old password.

use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

public function updateprofile(Request $request)
{
    // Validate input
    $request->validate([
        'password' => 'required|min:8|confirmed',
    ]);

    // Get the logged-in user's ID
    $id = Auth::user()->id;

    // Retrieve the hashed password from the database
    $user = DB::table('users')->where('id', $id)->select('password')->first();
    $hashedPassword = $user->password;

    // Check if the new password is the same as the old password
    if (Hash::check($request->password, $hashedPassword)) {
        return back()->withErrors(['password' => 'The new password cannot be the same as the old password.']);
    }

    // Hash the new password
    $newHashedPassword = Hash::make($request->password);

    // Update the user's password in the database
    DB::table('users')->where('id', $id)->update([
        'password' => $newHashedPassword,
    ]);

    return redirect()->back()->with('success', 'Profile updated successfully.');
}

Explanation

  • Form HTML:
    • Ensures both password and password_confirmation fields are present and have the password type for security.
    • Uses @csrf for CSRF protection.
    • Displays validation errors if they exist.
  • Controller Method:
    • Validate Input: Uses the confirmed rule to ensure password and password_confirmation match and that the password has a minimum length of 8 characters.
    • Retrieve Old Password: Fetches the stored hashed password from the database for the currently logged-in user.
    • Compare Passwords: Uses Hash::check() to verify if the new password matches the old password hash. If they match, an error is returned.
    • Hash and Update New Password: Hashes the new password and updates it in the database if the new password does not match the old password.

By following this guide, you can ensure that users’ new passwords are properly validated, confirmed, and do not match their old passwords, providing a more secure and user-friendly experience.