zoukankan      html  css  js  c++  java
  • Laravel 5.8 做个知乎 14 —— 用户关注

    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 esourcesviewsquestionsshow.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  appUser.php

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

    2.3 esourcesjscomponentsUserFollowButton.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 appRepositoriesUserRepository.php

    <?php
    namespace AppRepositories;
    
    use AppUser;
    
    /**
     * Class UserRepository
     * @package AppRepositories
     */
    class UserRepository
    {
        /**
         * @param $id
         * @return mixed
         */
        public function byId($id)
        {
            return User::find($id);
        }
    }
    View Code

    2.5 appHttpControllersApiFollowersController.php

    <?php
    
    namespace AppHttpControllersApi;
    
    use AppRepositoriesUserRepository;
    use IlluminateHttpRequest;
    use AppHttpControllersController;
    use IlluminateSupportFacadesAuth;
    
    class FollowersController extends Controller
    {
        //
        protected $user;
        public function __construct(UserRepository $user)
        {
            $this->user = $user;
            $this->middleware('auth:api')->only('index','follow');
        }
        
        /**
         * 查看是否已关注
         * @param IlluminateHttpRequest $request
         *
         * @return IlluminateHttpJsonResponse
         */
        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 outesapi.php

    // 用户关注用户接口
    Route::get('/user/followers/{user}','ApiFollowersController@index');
    
    Route::post('/user/follow','ApiFollowersController@follow');
  • 相关阅读:
    WinAPI: SetRect 及初始化矩形的几种办法
    [书目20080225]软件工程与项目管理解析
    [转]npkcrypt 服务启动失败
    CPU是为用户服务的
    Web.config基础
    VBScript学习
    [书目20080130]如何成功管理一个软件项目
    [转]DB2常用命令大全
    [转]C++语法概括及其示例(示例代码下载)
    用友华表Cell产生柱状图表
  • 原文地址:https://www.cnblogs.com/polax/p/15063984.html
Copyright © 2011-2022 走看看