Laravel study notes (18) to take attention off

  1. Establishing an interim table
artisan make:migration --create=followers create_followers_table
    public function up()
    {
        Schema::create('followers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->integer('user_id');
            $table->integer('follower_id');
        });
    }
artisan migrate
  1. Generate routes
Route::get('follow/{user}', 'UserController@followToggle')->name('follow');
  1. front end
    <div class="text-center">
        <a href="{{route('follow', $user)}}" class="btn btn-success">{{$followerType}}</a>
    </div>
  1. User Model

Here is the main model of microblogging

	// 作者的关注者
    public function follower() {
        return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id');
    }

	// 作者关注的人
    public function following() {
        return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id');
    }

	// 判断作者是否已经被关注,此处$id为Auth::user()->id
    public function isFollower($id) {
        return $this->follower()->wherePivot('follower_id', $id)->first();
    }

	// 自动切换
    public function followerToggle($ids) {
        $ids = is_array($ids) ?: [$ids];
        return $this->follower()->withTimestamps()->toggle($ids);
    }
  1. Controller
   public function show(User $user)
    {
    	// 判断是否已经关注,并返回前台按钮
        $followerType = $user->isFollower(Auth::user()->id)? '取消关注' : '关注';
        $blogs = $user->blogs()->paginate(10);
        return view('user.show', compact('user','blogs', 'followerType'));
    }
    
    // 切换关注状态
    public function followToggle(User $user) {
        $user->followerToggle(Auth::user()->id);
        return back();
    }
Published 40 original articles · won praise 0 · Views 774

Guess you like

Origin blog.csdn.net/qj4865/article/details/104253761