【问题标题】:Trying to get property 'password' of non-object", exception: "ErrorException"试图获取非对象的属性“密码”,异常:“ErrorException”
【发布时间】:2020-11-03 07:30:08
【问题描述】:
 Laravel change password thrown with the  message of Trying to get property 'password' of non-object", exception:  

如何解决message: Trying to get property 'password' of non-object",异常: “ErrorException”请帮助..................................................

 public function updateAuthUserPassword(Request $request)
 {
    $this->validate($request, [
        'current' => 'required',
        'newpassword' => 'required',
        'password_confirmation' => 'required|same:newpassword'
    ]);

    $user = User::find(Auth::id());

    if (!Hash::check($request->current, $user->password)) {
        return response()->json(['errors' => ['current'=> ['Current password does not match']]], 
    422);
    }

    $user->password = Hash::make($request->newpassword);
    $user->save();

    return $user;
    }

【问题讨论】:

  • 确保 $user 不为空

标签: laravel vue.js


【解决方案1】:

改变

$user = User::find(Auth::id());

$user = User::findOrFail(Auth::id());

findOrFail 将接受一个 id 并返回一个模型。如果不存在匹配的模型,则抛出 ModelNotFoundException。 您也可以使用 try catch 块捕获异常。

所以你可以把你的完整代码写成

public function updateAuthUserPassword(Request $request)
 {
try{
   .... other codes
   $user = User::findOrFail(Auth::id());
}catch(ModelNotFoundException $e){
    // return with message that no user found.
}
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2018-04-14
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多