私はソーシャルネットワークを作成するチュートリアルに従います.Ajax(新しいエントリを追加)を使用してデータベースで行が利用できないときに好き嫌いの機能が壊れています。私は、次のよ
チュートリアル - このビデオは、彼がコントローラを作成する場所です:
https://www.youtube.com/watch?v=drM19VKbCgU&list=PL55RiY5tL51oloSGk5XdO2MGjPqc0BxGV&index=20
投稿エラーEloquentを使用して新しい行を追加
開発的環境:
- PhpStormのV9.0
- XAMPPのv3.2.2
- jQueryのv1.12.0
- Google Chrome
エラーim年齢:
Error image link
サイクル全体:
Likeして嫌いボタン(ビュー):
<a href="#" class="like">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ?
Auth::user()->likes()->where('post_id', $post->id)->first()->like == 1 ?
'You like this post':'Like' : 'Like' }}</a> |
<a href="#" class="like">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ?
Auth::user()->likes()->where('post_id', $post->id)->first()->like == 0 ?
'You don\'t like this post':'Dislike' : 'Dislike' }}</a>
<script>
var urlLike = '{{ route('like') }}';
</script>
ルート:
Route::post('/like', [
'uses' => '[email protected]',
'as' => 'like'
]);
リスナー+ Ajaxのコール:
$('.like').on('click', function(event){
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
var isLike = event.target.previousElementSibling == null;
//console.log(postId+' '+isLike);
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, postId: postId, _token: token}
})
.done(function(){
console.log(event.target.innerText);
event.target.innerText = isLike ? event.target.innerText == 'Like' ? 'You like this post':'Like' : event.target.innerText == 'Dislike' ? 'You don\'t like this post':'Dislike' ;
if(isLike){
event.target.nextElementSibling.innerText = 'Dislike';
} else{
event.target.nextElementSibling.innerText = 'Like';
}
});
});
コントローラー:
public function postLikePost(Request $request){
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true';
$update = false;
$post = Post::find($post_id);
if(!$post){
return null;
}
$user = Auth::user();
$like = $user->likes()->where('post_id', $post_id)->first();
if($like){
$already_like = $like->like;
$update = true;
if($already_like == $is_like){
$like->delete();
return null;
}
}else{
$like->like = $is_like;
$like->post_id = $post_id;
$like->user_id = $user_id;
}
// This is working when the controller is updating but broken when saving
if($update){
$like->update();
} else{
$like->save();
}
return null;
}
P.S:私はあなたがデバッグする良い方法を知っていれば/ログ/日食のように変数の値を見て、phpstormとlaravelする新たなんだ
は、それをいただければ幸いです。私はそれが代わりにlocalhost/your_project/public/like
$.ajax({
method: 'POST',
url: 'like',
data: {isLike: isLike, postId: postId, _token: token}
})
が動作するはずのlocalhost/public/likes
を要求して、AJAXリクエストが間違ったURLを使用して表示されるものと
devツールのネットワークタブを開いてリクエストをクリックすると、実際のエラーの内容がわかります – Sherif