📅  最后修改于: 2023-12-03 15:02:39.124000             🧑  作者: Mango
在 Laravel 中,更改用户密码时需要进行验证。本文将介绍如何在 Laravel 中进行密码更改验证。
<form action="/change-password" method="POST">
@csrf
<label for="new_password">New Password:</label>
<input type="password" name="new_password" id="new_password">
<label for="confirm_password">Confirm Password:</label>
<input type="password" name="confirm_password" id="confirm_password">
<button type="submit">Change Password</button>
</form>
Route::post('/change-password', 'UserController@changePassword');
changePassword
方法,使用 Laravel 内置的验证规则和消息。use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
public function changePassword(Request $request)
{
$user = Auth::user();
$validator = Validator::make($request->all(), [
'new_password' => 'required|min:6|different:password',
'confirm_password' => 'required|same:new_password',
], [
'new_password.required' => 'The new password field is required.',
'new_password.min' => 'The new password must be at least 6 characters.',
'new_password.different' => 'The new password and old password must be different.',
'confirm_password.required' => 'The confirm password field is required.',
'confirm_password.same' => 'The confirm password and new password must match.',
]);
if ($validator->fails()) {
return redirect('/dashboard')
->withErrors($validator)
->withInput();
}
$user->password = bcrypt($request->new_password);
$user->save();
return redirect('/dashboard');
}
其中,$user = Auth::user()
获取当前用户,Validator::make()
方法用于创建验证器实例,$validator->fails()
方法检查验证是否失败,withErrors()
方法将错误消息返回给视图,withInput()
方法将表单输入值返回到视图,bcrypt()
方法用于加密密码。
本文介绍了如何在 Laravel 中进行密码更改验证。在控制器中使用 Laravel 内置的验证规则和消息可轻松地验证表单数据。