簡體   English   中英

未定義的屬性:App\Http\Controllers\UserController::$user

[英]Undefined property: App\Http\Controllers\UserController::$user

public function doFollow($id)
{
    $user = $this->user->getById($id);        

    if (Auth::user()->isFollowing($id)) {
        Auth::user()->unfollow($id);
    } else {
        Auth::user()->follow($id);

        $user->notify(new FollowedUser(Auth::user()));
    }

    return redirect()->back();
}

在您檢查您的 UserController class 是否具有 $user 屬性之前,您必須在 class 構造函數中進行初始化。

use App\User;

class UserController extends Controller{

    private $user;

    public function __construct(User $user){
        // İnitialize user property.
        $this->user = $user;
    }

}

如果問題沒有解決。 檢查您的getById方法,如下所示。

您的getById方法返回 null object 並且您嘗試訪問 null ZA8CFDE6331BD59EB2AC96F8911C4B 中的屬性是未定義的屬性。

查看getById方法以返回現有用戶 Object。 檢查您的查詢並將find($id)更改為findOrFail($id) 當通過給定的$id查詢未找到用戶時,它會拋出錯誤。

或者,如果用戶存在,您可以檢查並執行工作:

public function doFollow($id)
{
    $user = $this->user->getById($id);

    if($user){
        if (Auth::user()->isFollowing($id)) {
            Auth::user()->unfollow($id);
        } else {
            Auth::user()->follow($id);

            $user->notify(new FollowedUser(Auth::user()));
        }
    }
    return redirect()->back();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM