Php 如果$user->save()失败,请取消在Laravel中重置密码
提醒控制器的默认postReset操作具有以下用于重置密码的代码:Php 如果$user->save()失败,请取消在Laravel中重置密码,php,laravel,Php,Laravel,提醒控制器的默认postReset操作具有以下用于重置密码的代码: $response = Password::reset($credentials, function($user, $password) { $user->password = Hash::make($password); $user->save(); }); 我想添加一个条件,以在save方法因任何原因失败时取消重置。我的模型在保存事件上调用验证函数,因此如果字段未验证,$user->save将
$response = Password::reset($credentials, function($user, $password)
{
$user->password = Hash::make($password);
$user->save();
});
我想添加一个条件,以在save方法因任何原因失败时取消重置。我的模型在保存事件上调用验证函数,因此如果字段未验证,$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变量。。。那么,有什么办法可以做到这一点吗?当然,如果你使用vanilla Laravel,用户保存并不意味着它会被验证。您需要在保存之前亲自验证用户,并在验证失败时重定向回错误,而不是在保存失败时。即。您需要使用如下代码:
if($validator->fails() || !$user->save())
{
return Redirect::back()->with('error', 'Failed to save');
}
其中,$validator是具有您的规则的验证器的实例。我已经能够通过抛出异常来解决此问题,如下所示:
您如何测试/模拟失败的保存?另外,顶部代码块缺少分号。我正在发布一个无法验证的密码。我已经在用户模型上定义了验证规则,我在validator->fails上放了一个骰子,我看到它没有验证密码的验证规则是什么?您提交的密码是什么?验证规则至少为8个字符,并且我提交的密码少于$response始终为非false,因为。可能是您以错误的方式使用了密码facade。或者尝试使用异常抛出而不是returnyes,但我对保存、创建和更新事件进行了验证,因此如果save未验证,则应返回false
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;
}