【发布时间】:2019-03-05 01:59:26
【问题描述】:
我对 Laravel、AJAX 等非常陌生。我是一名从事 Twitter 类型项目的学生,这是我提出的第一个堆栈问题。我试图寻找答案,但我的老师帮助我的代码与其他示例非常不同。我很确定我的问题出在我的“推文控制器”中的不同方法......非常感谢任何帮助!希望我已经提供了足够的信息,并希望这可以在未来对其他人有所帮助:)
这是我的错误:[1]:https://i.stack.imgur.com/zkxsd.png
POST http://localhost:8000/tweets/19/unlike 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (app.js:14253)
at settle (app.js:35706)
at XMLHttpRequest.handleLoad (app.js:14127)
这是我的喜欢表/迁移
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLikesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->increments('id');
$table->integer('tweet_id');
$table->integer('user_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('likes');
}
}
这是我的推文控制器
public function like($id){
$like = Like::create([
'user_id'=>auth()->id(),
'tweet_id'=> $id
]);
if($like){
return json_encode(array('status' => 'success'));
}
return json_encode(array('status' => 'failed'));
}
public function unlike($id){
$like = Like::delete([
'user_id'=>auth()->id(),
'tweet_id'=> $id
]);
if($like){
return json_encode(array('status' => 'success'));
}
}
这是我的网络路由
Route::post('tweets/{tweet}/like', 'TweetController@like');
Route::delete('tweets/{tweet}/like', 'TweetController@unlike');
这是我的模特
public function likes(){
return $this->hasMany(Like::class);
}
public function likedByCurrentUser(){
$userId=auth()->id();
//like boolean
$like = $this->likes->first(function($v) use ($userId){
//$v is a reference to the single like
return $v->user_id == $userId;
});
//if the user has liked a post
if($like){
return true;
}
return false;
}
这是我的 Vue 组件:
<script>
export default {
name: 'likeButton',
props: ['likeCount','hasLiked','tweetId','csrf'],
mounted(){
this.dataLikeCount = this.likeCount;
this.dataHasLiked = this.hasLiked;
},
data(){
return{
dataLikeCount:0,
dataHasLiked:false
}
},
methods:{
doLike(){
var type='like';
if(this.dataHasLiked){
type='unlike'
}
axios({
method:'POST',
url:'/tweets/' + this.tweetId + '/'+ type,
headers:{
'X-CSRFToken':this.csrf
},
json: true
}).then((response) => {
if(response.data.status == 'success'){
// response was successful (regardless of type)
return true
// if type is like
// add one to like count, set hasLiked to true
if(type == 'like'){
this.dataLikeCount++
}
// if type is unlike
// deduct one from like count, set hasLiked to false
if(type =='unlike'){
return false
this.dataLikeCount--
}
}
});
}
}
}
</script>
<template>
<div>
<button type="submit"
:class="{'btn btn-link':dataHasLiked}"
@click="doLike">
<i class="star"></i>
Like {{ dataLikeCount }}
</button>
</div>
</template>
【问题讨论】:
-
你能分享你的浏览器调试控制台网络吗
-
我编辑了我的帖子。这有帮助还是您需要更多?对不起,就像我说的,这是新手。当您单击错误链接时,它显示的与网络选项卡中的不同,然后是一大堆提到路由的东西。
标签: ajax laravel eloquent facebook-like