You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现密码修改?表单仅更新地址、邮箱及密码的技术咨询

Fixing Password Update with Old Password Validation in Laravel

Let’s walk through how to properly implement the password update feature with old password verification, while keeping address and email updates working smoothly. Here’s the revised code for each part:

1. Update the Form (edit.blade.php)

First, we need to add an old password field for identity verification, fix the password input type for security, and make password fields optional so users can update just their address/email without changing their password:

<form method="POST" action="{{ route('update') }}">
    @csrf
    {{ method_field('PATCH') }}

    <!-- Email Field -->
    <div class="form-group row">
        <label for="email" class="col-md-1 col-form-label text-md-right">{{ __('Email') }}</label>
        <div class="col-md-5">
            <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" 
                   name="email" value="{{ old('email') ?: auth()->user()->email }}" 
                   required autocomplete="email">
            @error('email')
                <span class="invalid-feedback" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
            @enderror
        </div>
    </div>

    <!-- Old Password (required only if changing password) -->
    <div class="form-group row">
        <label for="old_password" class="col-md-1 col-form-label text-md-right">{{ __('Old Password') }}</label>
        <div class="col-md-5">
            <input id="old_password" type="password" class="form-control @error('old_password') is-invalid @enderror" 
                   name="old_password" autocomplete="current-password">
            @error('old_password')
                <span class="invalid-feedback" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
            @enderror
        </div>
    </div>

    <!-- New Password (required only if changing password) -->
    <div class="form-group row">
        <label for="password" class="col-md-1 col-form-label text-md-right">{{ __('New Password') }}</label>
        <div class="col-md-5">
            <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" 
                   name="password" autocomplete="new-password">
            @error('password')
                <span class="invalid-feedback" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
            @enderror
        </div>
    </div>

    <!-- Address Field -->
    <div class="form-group row">
        <label for="address" class="col-md-1 col-form-label text-md-right">{{ __('Address') }}</label>
        <div class="col-md-5">
            <textarea id="address" class="form-control @error('address') is-invalid @enderror" 
                      name="address" required autocomplete="address">{{ old('address') ?: auth()->user()->address }}</textarea>
            @error('address')
                <span class="invalid-feedback" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
            @enderror
        </div>
    </div>

    <div class="form-group row mb-0">
        <div class="col-md-1">
            <button type="submit" class="btn btn-block btn-primary">
                {{ __('Update Profile') }}
            </button>
        </div>
    </div>
</form>

Key changes here:

  • Changed password input type from text to password for security
  • Added the old_password field for verification
  • Removed required from password fields so users can skip password updates
  • Updated the submit button text to reflect the actual action
  • Used auth()->user() instead of user() for standard Laravel syntax

2. Update the Controller Logic (RegisterController.php)

Next, we’ll add proper validation rules, fix the old password check, and ensure all changes are saved to the database:

use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

public function sqlupdate(Request $request) {
    // Validate incoming request data
    $validated = $request->validate([
        'email' => 'required|email|unique:users,email,' . auth()->id(),
        'address' => 'required|string',
        'old_password' => 'nullable|string',
        'password' => 'nullable|string|min:8', // Add `|confirmed` if you want a password confirmation field
    ]);

    // Get the authenticated user
    $user = auth()->user();

    // Update email and address first
    $user->update([
        'email' => $validated['email'],
        'address' => $validated['address'],
    ]);

    // Handle password update if the user provided a new password
    if ($request->filled('password')) {
        // Validate old password is provided and correct
        if (!$request->filled('old_password') || !Hash::check($request->old_password, $user->password)) {
            throw ValidationException::withMessages([
                'old_password' => ['Your old password is incorrect.'],
            ]);
        }

        // Update and save the new password
        $user->password = Hash::make($validated['password']);
        $user->save();
    }

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

Key fixes and improvements:

  • Added validation rules:
    • Ensures the email is unique (excluding the current user to avoid conflicts)
    • Requires old_password only when password is filled
    • Enforces a minimum password length (adjust min:8 as needed)
  • Fixed the password update logic: your original code didn’t save the password change with $user->save()
  • Uses $request->filled() to check if a password was provided (more reliable than checking for empty values)
  • Throws a validation error if the old password is missing or incorrect, which displays in the form’s error area
  • Added a success flash message to notify the user of a successful update

3. (Optional) Update the Route

While your existing route works, using PATCH aligns with RESTful conventions for updating resources, matching the {{ method_field('PATCH') }} in your form:

Route::patch('update', 'Auth\RegisterController@sqlupdate')->name('update');

How It Works

  • If the user only updates their email/address: They don’t need to fill in password fields, and the update happens immediately.
  • If the user wants to change their password: They must provide both their old_password (to verify identity) and new_password, which gets validated before the update.

内容的提问来源于stack exchange,提问作者user9975473

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:32:44