如何在关注或取消关注(附加)之前检查用户是否关注另一个人

How to check if user is following the other one before following or unfollowing (attach)

我在我的用户table中使用了多对多的关系来让登录的用户关注另一个用户,但我自己没有弄清楚,我检查了其他人做了什么并尝试做类似的东西并且有效。在我的方法中,我有:

function follow(User $user) {
    $this->followers()->attach($user->id);
}

function unfollow(User $user) {
    $this->followers()->detach($user->id);
}

这让我可以关注。

table 与函数相关,例如:

return $this->belongsToMany('App\User', 'followers', 'user_id', 'follower_id');

现在我通过控制器传递 $user 值,控制器非常简单:

    $userId = User::find($user);
    $willfollow = Auth::user();

    $willfollow->unfollow($userId);

我知道可能不需要控制器信息,但如果很容易检查控制器内的关系,我更愿意那样做,因为我显然对方法没有那么多了解使用。

我正在使用 Laravel 5.4。

因为Laravel 5.3你可以使用syncWithoutDetaching(最有效):

$this->followers()->syncWithoutDetaching([$user->id]);

其他方式:

$this->followers()->sync([$user->id], false);

保存前检查是否存在(仅当您已经加载时有效$this->followers):

function follow(User $user) {
    if(!$this->followers->contains($user)) {
        $this->followers()->attach($user->id);
    }
}