小白兔晒黑了

导航

 

1 创建表

php artisan make:migration create_followers_table --create=followers

 

    public function up()
    {
        Schema::create('followers', function (Blueprint $table) {
            $table->bigIncrements('id');
            //关注者id
            $table->integer('follower_id')->unsigned()->index();
            //被关注者id
            $table->integer('followed_id')->unsigned()->index();
            $table->timestamps();
        });
    }

 

php artisan migrate

2 代码

2.1 \resources\views\questions\show.blade.php

 <div class="card">
                    <div class="card-header follow">
                        <h5>关注作者</h5>

                    </div>
                    <div class="card-body">
                        <div class="media">
                            <div class="media-left">
                                <a href="#">
                                    <img width="36px;" src="{{$question->user->avatar}}" alt="{{$question->user->name}}">
                                </a>
                            </div>
                        </div>
                        <div class="media-body">
                            <h4 class="media-heading">
                                <a href="">{{$question->user->name}}</a>
                            </h4>
                        </div>
                        <div>
                            <span>问题</span>
                            <span>{{$question->user->questions_count}}</span>
                            <span>答案</span>
                            <span>{{$question->user->answers_count}}</span>
                            <span>评论</span>
                            <span>{{$question->user->comments_count}}</span>
                        </div>
                        <!-- vue 组件 -->
                        <user-follow-button user="{{$question->user_id}}"></user-follow-button>
                        <!-- vue 组件 -->
                        <send-message user="{{$question->user_id}}"></send-message>
                    </div>
                </div>
View Code

2.2  app\User.php

//关注用户
    public function followersUser()
    {
        //1 类 2 表名 3 外键 4 外键
        return $this->belongsToMany(self::class, 'followers', 'followed_id', 'follower_id')->withTimestamps();
    }

2.3 \resources\js\components\UserFollowButton.vue

<template>
    <button class="btn  "
            v-text="text"
            v-on:click="follow"
            v-bind:class="{'btn-success':followed,'btn-info':!followed}">
    </button>
</template>

<script>
    export default {
        name: "UserFollowButton",
        props:['user'],
        // mounted是vue中的一个钩子函数,一般在初始化页面完成后,再对dom节点进行相关操作
        mounted(){
            axios.get('/api/user/followers/' + this.user).then(res => {
                this.followed = res.data.followed
            },error => {
                //console.log(error);
                //console.log(error.response.status)
                if(error.response.status==401){
                    this.auth = false
                }

            })
        },
        data(){
            return {
                followed:false ,
                auth:true
            }
        },
        computed:{
            text(){
                if (!this.auth){
                    return '登录后关注'
                }
                return this.followed ? '关注get':'关注ta'
            }
        },

        methods:{
            follow(){
                //alert('Hello')
                axios.post('/api/user/follow',{'user':this.user}).then(res => {
                    this.followed = res.data.followed;
                    console.log(res);
                    console.log(res.data)
                })
            }
        }
    }
</script>

<style scoped>

</style>
View Code

2.4 \app\Repositories\UserRepository.php

<?php
namespace App\Repositories;

use App\User;

/**
 * Class UserRepository
 * @package App\Repositories
 */
class UserRepository
{
    /**
     * @param $id
     * @return mixed
     */
    public function byId($id)
    {
        return User::find($id);
    }
}
View Code

2.5 \app\Http\Controllers\Api\FollowersController.php

<?php

namespace App\Http\Controllers\Api;

use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class FollowersController extends Controller
{
    //
    protected $user;
    public function __construct(UserRepository $user)
    {
        $this->user = $user;
        $this->middleware('auth:api')->only('index','follow');
    }
    
    /**
     * 查看是否已关注
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($id)
    {
       //被关注者
       $user = $this->user->byId($id);
       $followers = $user->followersUser()
         ->pluck('follower_id')->toArray();
       $uid = Auth::guard('api')->user()->id;
       if( in_array($uid,$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]);
    }
}
View Code

2.6 \routes\api.php

// 用户关注用户接口
Route::get('/user/followers/{user}','Api\FollowersController@index');

Route::post('/user/follow','Api\FollowersController@follow');

 

posted on 2021-07-27 01:52  小白兔晒黑了  阅读(41)  评论(0编辑  收藏  举报