未定义的属性: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 类是否具有属性之前$user如果没有,则必须在类构造函数中初始化。

use AppUser;
class UserController extends Controller{
private $user;
public function __construct(User $user){
// İnitialize user property.
$this->user = $user;
}
}

如果问题没有解决。检查您的getById方法,如下所示。

您的getById方法返回 null 对象,并且您尝试访问 null 对象中的属性,因此它是未定义的属性。

查看返回现有用户对象getById方法。检查查询并将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();
}

最新更新