一、创建模型
创建点赞模型
php artisan make:model Vote -m
修改生成的 database/migrations/create_votes_table.php
public function up()
{
Schema::create('votes', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->unsignedInteger('answer_id')->index();
$table->timestamps();
});
}
执行数据迁移
php artisan migrate
修改 app/User.php
public function votes()
{
return $this->belongsToMany(Answer::class, 'votes')->withTimestamps();
}
public function voteFor($answer)
{
return $this->votes()->toggle($answer);
}
public function hasVotedFor($answer)
{
return !! $this->votes()->where('answer_id', $answer)->count();
}
修改 app/Repositories/AnswerRepository.php
public function byId($id)
{
return Answer::find($id);
}
二、创建控制
php artisan make:controller VotesController
修改 app/Http/Controllers/VotesController.php
namespace App\Http\Controllers;
use App\Repositories\AnswerRepository;
use Auth;
use Illuminate\Http\Request;
class VotesController extends Controller
{
protected $answer;
public function __construct(AnswerRepository $answer)
{
$this->answer = $answer;
}
public function index(Request $request)
{
if(user('api')->hasVotedFor($request->get('answer'))){
$voted = true;
}else{
$voted = false;
}
return response()->json(['voted'=>$voted]);
}
public function vote()
{
$answer = $this->answer->byId(request('answer'));
$userToVote = user('api')->voteFor(request('answer'));
if(count($userToVote['attached']) > 0){
$answer->increment('votes_count');
$voted = true;
}else{
$answer->decrement('votes_count');
$voted = false;
}
return response()->json(['voted'=>$voted]);
}
}
修改 routes/api.php
Route::post('/answer/voter', 'VotesController@index')->middleware('auth:api');
Route::post('/answer/vote', 'VotesController@vote')->middleware('auth:api');
三、创建视图
新建 resources/assets/js/components/UserVoteButton.vue
注册组件:修改 resources/assets/js/app.js
Vue.component('user-vote-button', require('./components/UserVoteButton.vue'));
执行 gulp
gulp
修改 resources/views/questions/show.blade.php
访问:http://127.0.0.1:8000/questions/id,id 为问题 ID
点击按钮进行测试