laravel toggle方法

toggle方法主要用于多对多关系中,attach detach 比如点赞 收藏

1.user表

2.post表 title content

3.中间表 favoriate user_id post_id

4.user中定义关系

 public function favorites(){
    return $this->belongsToMany(Post::class,'favoriates'); //第二个参数中间表
}

5.关联关系

做法一:

在tinker中操作

$user = AppUser::find(1);
$post = AppPost::find(2);
$user->favorite()->attach($post);
查看结果:$user->refresh()->favorite

//取消收藏
 $user->favorite()->detach($post);

做法二:toggle 不用去判断用户有没有收藏该文章 用户收藏了则取消收藏 反之则收藏

$user->favorite()->toggle($post);
原文地址:https://www.cnblogs.com/webskill/p/7464403.html