具有AJAX发布请求的Laravel 5.8 Likes系统不起作用 [英] Laravel 5.8 Likes system with AJAX Post Request Not Working

查看:63
本文介绍了具有AJAX发布请求的Laravel 5.8 Likes系统不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel中为我的食谱应用程序构建了一个Like系统,但无法使我的AJAX POST请求生效.只是根本没有碰到我的控制器,所以我无法存储任何喜欢的东西.我在三个模型之间有关系,例如用户",食谱".我的数据库中有个人喜欢表.代码如下:

I am building a Like system for my recipe application in Laravel and I am not able to get my AJAX POST request to function. It just simply isn't hitting my controller, so I am not able to store any likes. I have a relationship between three models, Like, User, Recipe. I have an individual likes table in my DB. The code is the following:

我的模型喜欢

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Like extends Model
{

    protected $table = 'likes';


    // Get all of the recipes that are assigned this like
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function recipes(){
        return $this->belongsTo('App\Recipe');
    }
}

用户

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'username', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function recipes(){
        return $this->hasMany('App\Recipe');
    }

    public function likes(){
        return $this->hasMany('App\Like');
    }
}

食谱

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Recipe extends Model
{
    //Table Name
    protected $table = 'recipes';
    // Primary Key
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;

    public function user(){
        return $this->belongsTo('App\User');
    }

    public function category(){
        return $this->belongsTo('App\Category');
    }

    public function comments(){
        return $this->hasMany('App\Comment'); 
    }

    public function likes(){
        return $this->hasMany('App\Like');
    }
}

AJAX

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

// Likes AJAX
var recipeId = 0;

$('.like').on('click', function(event) {
    event.preventDefault();
    var isLike = event.target.previousElementSibling == null;
    recipeId = event.target.parentNode.parentNode.dataset['recipeid'];

    $.ajax({
        method: 'POST',
        url: urlLike,
        data: {isLike: isLike, recipeId: recipeId},
        success: function(data){
            console.dir(data);
            }
    })
        .done(function() {
            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.previousElementSibling.innerText = 'Like';
            }
        });
});

控制器方法

 public function likeRecipe(Request $request){

        $recipe_id = $request['recipeId'];
        $is_like = $request['isLike'] === 'true';
        $update = false;
        $recipe = Recipe::find($recipe_id);
        if (!$recipe) {
            return null;
        }
        $user = Auth::user();
        $like = $user->likes()->where('recipe_id', $recipe_id)->first();
        if ($like) {
            $already_like = $like->like;
            $update = true;
            if ($already_like == $is_like) {
                $like->delete();
                return null;
            }
        } else {
            $like = new Like();
        }
        $like->like = $is_like;
        $like->user_id = $user->id;
        $like->recipe_id = $recipe->id;
        if ($update) {
            $like->update();
        } else {
            $like->save();
        }
        return null;
}

当我弄乱AJAX文件时,我遇到各种HTTP错误,但是它永远无法正常工作.请帮忙!预先谢谢你!

I'm getting various HTTP errors thrown at me as I mess with the AJAX file, but it is never working. Please help! Thank you in advance!

推荐答案

在这种情况下.您需要学习如何针对ajax请求正确调试.有五千个原因返回500错误.

In this kind of situation. You need learn how to debug properly for ajax request. There are thousand reason for return 500 error.

第一步:确保您的Ajax函数正确点击了您的网址.制作一个简单的方法,然后 dd().

1st step: make sure your ajax function hit your url properly. Make a simple method and dd() something.

public function likeRecipe(Request $request){
     dd('Yes! it working !');
}

转到浏览器,右键单击并检查,然后转到网络"选项卡,您可以看到您的请求.单击您的请求,然后查找响应"选项卡.在那里,您可以找到发生的确切情况.

Go to your browser right click and Inspect then go to Network tab then you can see your request. Click on your request then look for response tab.There you can find exactly what happened.

这篇关于具有AJAX发布请求的Laravel 5.8 Likes系统不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆