Laravel 5.8 Система лайков с почтовым запросом AJAX не работает - PullRequest
2 голосов
/ 01 апреля 2019

Я создаю систему Like для своего приложения рецептов в Laravel и не могу заставить работать мой запрос 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;
}

Я получаю различные ошибки HTTP, возникающие в процессе работы с файлом AJAX, но он никогда не работает. Пожалуйста помоги! Заранее спасибо!

Ответы [ 2 ]

1 голос
/ 01 апреля 2019

В такой ситуации. Вам нужно научиться правильно отлаживать запрос ajax. Есть тысячи причин возврата 500 ошибок.

1-й шаг: убедитесь, что ваша функция ajax правильно работает с вашим URL. Сделай простой метод и dd() что-нибудь.

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

Перейдите в браузере, щелкните правой кнопкой мыши и проверьте, затем перейдите на вкладку Сеть, после чего вы сможете увидеть свой запрос. Нажмите на ваш запрос, затем найдите вкладку ответа. Там вы можете найти именно то, что произошло.

0 голосов
/ 01 апреля 2019

405 означает, что ваша функция likeRecipe вообще не работает, а 500 означает, что есть какая-либо ошибка ответа, поэтому попробуйте удалить часть кода из функции likeRecipe, попробуйте снова, например, ваша первая попытка может быть:

public function likeRecipe(Request $request){
return null;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...