提醒控制器的默认 postReset() 操作具有以下用于重置密码的代码:
$response = Password::reset($credentials, function($user, $password)
{
$user->password = Hash::make($password);
$user->save();
});
我想添加一个条件,以便在保存方法失败(出于任何原因)时取消重置。我的模型在 saving() 事件上调用验证函数,因此如果字段未验证,$user->save() 返回 false。
我已经将我的代码修改为:
$response = Password::reset($credentials, function($user, $password)
{
$user->password = $password;
# validate before password hashing
if(!$user->validate()) {
Redirect::back()->with('error', 'Validator failed');
return false;
}
# hash password and try to save
$user->password = Hash::make($password);
if(!$user->save()) {
Redirect::back()->with('error', 'Validator failed');
return false;
}
});
if (!$response) {
return Redirect::back()->with('error', 'Validator failed');
}
但我看到关闭的返回不会影响$response变量......那么有什么想法可以做到这一点吗?
用户保存并不意味着它将被验证(当然,如果您使用香草 Laravel)。您需要在保存之前手动验证用户,并在验证失败时重定向回错误,而不是在保存失败时重定向回来。即您需要使用这样的代码:
if($validator->fails() || !$user->save())
{
return Redirect::back()->with('error', 'Failed to save');
}
其中$validator
是带有规则的验证器的实例。
我已经能够通过抛出异常来解决这个问题,根据新苦行僧的评论:
try {
$response = Password::reset($credentials, function($user, $password)
{
$user->password = Hash::make($password);
if(!$user->save()) {
# throw exception if save fails
throw new Exception(Password::INVALID_PASSWORD);
}
});
} catch ( Exception $e) {
$response = Password::INVALID_PASSWORD;
}