大佬教程收集整理的这篇文章主要介绍了Laravel 5.8 做个知乎 18 —— 点赞,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
public function up() { scheR_172_11845@a::create('votes', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedInteger('user_id')->index(); $table->unsignedInteger('answer_id')->index(); $table->timestamps(); }); }
php artisan migrate
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(); }
<template> <button class="btn btn-default" v-text="text" v-on:click.prevent="vote" v-bind:class="{'btn-success':voteD}"> </button> </template> <script> export default { name: "UserVoteButton", props:['answer','count'], // mounted是vue中的一个钩子函数,一般在初始化页面完成后,再对dom节点进行相关操作 mounted(){ axios.post('/api/answer/' + this.answer+'/votes/users').then(res => { this.voted = res.data.voted console.log(res.data); },error => { console.log(error); //console.log(error.response.status) if(error.response.status==401){ this.auth = false } }) }, data(){ return { voted:false , auth:true , count2:this.count } }, computed:{ text(){ return this.count2 } }, methods:{ vote(){ axios.post('/api/answer/vote',{'answer':this.answer}).then(res => { this.voted = res.data.voted res.data.voted ? this.count2++ : this.count2-- console.log(res.data) }) } } } </script> <style scoped> </style>
<?php namespace ApphttpControllersApi; use Illuminatehttprequest; use IlluminateSupportFacadesAuth; use ApphttpControllersController; use AppRepositoriesAnswerRepository; class VotesController extends Controller { /** * 答案仓库 */ protected $answer; /** * 初始化 */ public function __construct(AnswerRepository $answer) { $this->answer = $answer; } // public function users($id) { $user = Auth::guard('api')->user(); if($user->hasVotedFor($id)){ return response()->json(['voted'=>true]); } return response()->json(['voted'=>false]); } public function vote(request $request) { $answer = $this->answer->GetANSWERById($request->get('answer')); $voted = Auth::guard('api')->user()->voteFor($request->get('answer')); if(count($voted['attached']) > 0){ $answer->increment('votes_count'); // 作者被关注 return response()->json(['voted'=>true]); } $answer->decrement('votes_count'); // 取消作者被关注 return response()->json(['voted'=>false]); } }
// 点赞答案接口 Route::post('/answer/{iD}/votes/users','ApiVotesController@users'); Route::post('/answer/vote','ApiVotesController@vote');
以上是大佬教程为你收集整理的Laravel 5.8 做个知乎 18 —— 点赞全部内容,希望文章能够帮你解决Laravel 5.8 做个知乎 18 —— 点赞所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。