创建一个模型Follower并生成迁移文件,生成一个存放关注者和被关注者的表
php artisan make:model --migration Model/Follower;
在迁移文件里添加以下字段,然后运行迁移,生成表follower
$table->unsignedInteger ('user_id')->index()->comment('被关注者');
$table->unsignedInteger ('follower_id')->index()->comment('关注者,粉丝');
php artisan migrate//运行迁移,生成follower表
在模型Follower添加属性 fillable或者 guarded,fillable表示在执行数据填充时允许填充的字段,guarded表示不允许填充的字段
protected $fillable=['user_id','follower_id'];
protected $guarded=[];
取消关注和关注是用户之间的多对多的一种两个表之间的关联,关注者和被关注者都来自与users表,follower表里的两个字段user_id和follower_id都和users表格用户id关联,我们在用户模型User里来构建他们的关联
namespace App;//命名空间,这是User模型
//获得当前用户的粉丝有哪些
public function fans(){
//belongsToMany是多对多关联中定义关联的方法
//第一个参数,传入一个模型,是要关联的模型的名字
//第二个参数followers是中间表的名字
//第三个参数user_id是是这个模型定义在中间表中的外键
//第四个参数是follower_id是另一个模型定义在这个中间表的外键名
//此关联可以通过已知的user_id(当前用户id)来查询follower_id(粉丝id)
$this->belongsToMany (User::class,'followers','user_id','follower_id');
}
//获取当前用户(粉丝)所关注的用户的id
public function follower(){
//此关联可以通过follower_id(粉丝)来查找user_id(被关注者)
$this->belongsToMany (User::class,'followers','follower_id','user_id');
}
//判断当前登陆用户是否关注了$user(登陆用户正在浏览的文章或视频对应主人)
public function following(User $user){
//contains或者wherePivot 来过滤belongsToMany 返回的结果(true,false),
return $this->follower->contains($user);
}
用toggle方法来双向实现关注和取消关注时数据表的变化,给toggle绑定一个id($user->id),如果这个id已经在中间表中存在(关注),执行一次toggle,那么这个id在中间表中会被移除(取消关注)
public function follow(User $user){
//
auth ()->user ()->follower()->toggle([$user->id]);
return back ()->with ('success','操作成功');
}
路由的配置
//在跳转时要带上当前被关注或者被取消关注用户的信息参数
Route::get ( '/follow/{user}' , 'UserController@follow' )->name ( 'follow' );
页面布局
@if(auth()->user()->attention($article->user))
<a href="{{route('home.user.attentions',[$article->user])}}">
<button class="btn btn-white btn-block">
取消关注
</button>
</a>
@else
<a href="{{route('home.user.attentions',[$article->user])}}">
<button class="btn btn-white btn-block">
<span class="fe fe-plus "></span>
关注
</button>
</a>
@endif