1、resources\assets\js\components\UserFollowButton.vue中
<template>
<button class="btn btn-default"
v-bind:class="{'btn-success':followed}"
v-text="text"
v-on:click="follow"
>
</button>
</template>
<script>
export default {
props:['user'],
mounted() {
this.$http.get('/api/user/followers/' + this.user).then(response=>{
this.followed = response.data.followed;
});
},
data(){
return {
followed:false
}
},
computed:{
text(){
return this.followed?'已关注':'关注TA';
}
},
methods:{
follow() {
this.$http.post('/api/user/follow',{'user':this.user}).then(response=>{
this.followed = response.data.followed;
console.log(response.data.followed);
});
},
}
}
</script>
2、resources\assets\js\app.js注册组件
require('./bootstrap');
Vue.component('user-follow-button', require('./components/UserFollowButton.vue'));
const app = new Vue({
el: '#app'
});
3、api.php
Route::get('/user/followers/{id}','FollowersController@index');
Route::post('/user/follow','FollowersController@follow');
4、app\Http\Controllers\FollowersController.php
public function index($id){
$user = $this->user->byId($id);
$followers = $user->followersUser()->pluck('follower_id')->toArray();
if (in_array(\Auth::guard('api')->user()->id,$followers)){
return response()->json(['followed'=>true]);
}
return response()->json(['followed'=>false]);
}
public function follow(){
//明星
$userToFollow = $this->user->byId(\request('user'));
//粉丝:登录用户
$followed = \Auth::guard('api')->user()->followThisUser($userToFollow->id);
if(count($followed['attached'])>0){
$userToFollow->increment('followers_count');
return response()->json(['followed'=>true]);
}
$userToFollow->decrement('followers_count');
return response()->json(['followed'=>false]);
}
5、app\User.php
//关注用户
public function followers(){
return $this->belongsToMany(self::class,'followers','follower_id','followed_id')->withTimestamps();
}
public function followersUser(){
return $this->belongsToMany(self::class,'followers','followed_id','follower_id')->withTimestamps();
}
public function followThisUser($user){
return $this->followers()->toggle($user);
}
6、app\Repositories\UserRepository.php
namespace App\Repositories;
class UserRepository
{
public function byId($id){
return \App\User::find($id);
}
}
7、view
<user-follow-button user="{{$question->user_id}}"></user-follow-button>