martis martis - 3 months ago 15
Ajax Question

Laravel AJAX like button 500 (Internal Server Error)

I am trying to make AJAX like button in Laravel. Console returns me 500 (Internal Server Error). Here is my:

JavaScript

$(function(){
$('#likeForm').submit(function(e){
e.preventDefault();
var user = $('input[name="user_id"]').val();
var token = $('input[name="_token"]').val();
$.ajax({
url:'like-post',
type: 'POST',
data: {'_token': token, 'user': user },
dataType: 'JSON',
success: function() {
alert('succsess');
},
error: function(){
alert('error' );
}})})});


html.blade

<form method="POST" id="likeForm" action="">
<input type="hidden" name="user_id" value="{{$user->id}}" >
<a onclick="$('#likeForm').submit()"><span>
<span class="fa fa-heart"></span> Like</a>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>


Controler

public function likeUser (Request $r) {
$user_id = $r->input('user');
Favorite::create(['user_id' => Auth::user()->id, 'liked_id' => $user_id]);
}


and route

Route::post('like-post', 'FavoritesController@likeUser');

Answer

You can use remove Request from method signature and write the whole method in one line:

 public function likeUser () {
    Favorite::create(['user_id' => Auth::user()->id, 'liked_id' => \Request::get('user')]);
}
Comments