首页 > 解决方案 > 设置时更改密码

问题描述

我想在我的更新方法中更改密码,何时设置 $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,
         ]);

标签: laraveleloquent

解决方案


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()

推荐阅读