具有AJAX发布请求的Laravel 5.8 Likes系统不起作用

时间:2019-04-01 01:52:30

标签: php ajax laravel

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

我的模型 喜欢     

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错误,但是它永远无法正常工作。请帮忙!预先谢谢你!

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

405表示您的likeRecipe函数根本没有运行,而500表示没有响应错误,因此请尝试从likeRecipe函数中删除一些代码,然后重试,例如,您的第一次尝试可能是:

public function likeRecipe(Request $request){
return null;
}