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();
}
1 Answer
Before you can check your UserController class does have $user property if is not you must initialize in class constructor.
use App\User;
class UserController extends Controller{
private $user;
public function __construct(User $user){
// İnitialize user property.
$this->user = $user;
}
}
If problem was not solved. Check your getById method as below.
Your getById method returns null object and you try access property in null object so it is undefined property.
Look getById method for return existing User Object. Check your query and change find($id) to findOrFail($id). It throws Error when query not found user by given $id.
Or you can check and do job if user exists:
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();
}
$this->userin your __construct() method?$user = $this->user->getById($id);... try this instead$user = User::find($id);$this->userdefined?