Laravel 5.8 做個知乎 11 —— 新增關注 toggle方法 的使用
阿新 • • 發佈:2021-07-16
1 建立關注表資料
php artisan make:migration create_user_question_table --create=user_question
\database\migrations\2021_07_15_002200_create_user_question_table.php
public function up() { Schema::create('user_question', function (Blueprint $table) { $table->bigIncrements('id');View Code$table->integer('user_id')->unsigned()->index(); $table->integer('question_id')->unsigned()->index(); $table->timestamps(); }); }
php artisan migrate
2 model
2.1 Follow
php artisan make:model Follow
\app\Follow.php
<?php namespace App;View Codeuse Illuminate\Database\Eloquent\Model; class Follow extends Model { // protected $table = 'user_question'; protected $fillable = ['user_id','question_id']; }
2.2 User
\app\User.php
/* public function follows($question) { return Follow::create([ 'question_id' =>$question, 'user_id' =>$this->id ]); }View Code*/ public function follows() { return $this->belongsToMany(Question::class,'user_question') ->withTimestamps(); } public function followThis($question) { return $this->follows()->toggle($question); } public function followed($question) { return !! $this->follows()->where('question_id',$question)->count(); }
2.3 Question
\app\Question.php
public function followers() { return $this->belongsToMany(User::class,'user_question') ->withTimestamps(); }View Code
3 控制器
php artisan make:controller QuestionFollowController
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class QuestionFollowController extends Controller { public function __construct() { $this->middleware('auth'); } // public function follow($question) { Auth::user()->followThis($question); return back(); } }View Code
4 路由
\web.php
Route::get('questions/{question}/follow','QuestionFollowController@follow');
5 模板
\resources\views\questions\show.blade.php
<div class="col-md-3"> <div class="card"> <div class="card-header"> <h2>{{ $question->followers_count }}</h2> <span>關注者</span> </div> <div class="card-body"> <a href="/questions/{{$question->id}}/follow" class="btn {{Auth::check() && Auth::user()->followed($question->id) ? 'btn-success':'btn-info' }}"> {{Auth::check() && Auth::user()->followed($question->id) ?'已關注' :'關注該問題' }} </a> <a href="#container" class="btn btn-primary"> 撰寫答案 </a> </div> </div> </div>