laravel - 设置时更改密码
问题描述
我想在我的更新方法中更改密码,何时设置 $request->data['password'] 并且如果未设置旧密码则不为空,请替换这是我的代码,但我遇到了错误!
$user=Model::whereId($id)->update([
"updated_at" => Carbon::now(),
"department_id" => $department,
"username" => $request->data['username'],
'password'=>isset($request->data['password'])?bcrypt($request->data['password']):$user->password,
]);
解决方案
isset
检查请求中是否存在密码字段,但如果它存在并且为空,那么它仍然会通过。你的三元也是相反的。
你可以使用empty
你想要达到的目标:
'password'=>!empty($request->data['password'])?bcrypt($request->data['password']):$user->password,
但是,如果您想在那里使用三元组,那么您必须在此之前检索到您的用户模型,以便您的回退实际上具有数据库中用户密码的值。类似的方法是:
$user=Model::whereId($id)->first();
$user->updated_at = Carbon::now();
$user->department_id => $department;
$user->username = $request->data['username'];
if(!empty($request->data['password']){
$user->password=bcrypt($request->data['password']);
}
$user->save();
这样你就不需要后备。返回具有最新更改的用户模型,您可以在fresh()
之后使用该功能save()
return $user->fresh()
推荐阅读
- typescript - 如何在 TypeScript 中实现类型化的“both”函数?
- python - PyTorch 模型保存错误:“无法腌制本地对象”
- python - 单元测试:使用您正在测试的程序中的函数
- mysql - MySQL 使用 Debezium 对 Kafka 的更改 - 仅捕获 DDL stmts
- graph - 无法从 csv 加载 Cytoscape 中的节点表
- sql-server - 如何使用随机数生成真正的随机结果?ABS(CHECKSUM(NewID))) 不工作
- html - 如何修复无法读取 Angular 中的属性
- python - 簇/斑点检测
- ruby-on-rails - 扩展 Rails ThoughtBot/Clearance gem 以进行密码轮换
- firebase - 如何获取 Firebase 文档中的特定字段