Я создаю систему 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, но он никогда не работает. Пожалуйста помоги! Заранее спасибо!