How can I return a number of likes in laravel withe ajax

802 Views Asked by At

here is my app.blade

$('.like').click(function(event) {
    var id = $(this).data('id');
    $.ajax({
      url: "{{route('post.like','')}}/"+id,
    })
});  

and here is my AdsController.php

public function likePost(Request $request){  
    $likePost=new Like;
    $likePost->user_id=Auth::user()->id;
    $likePost->ad_id= $request->id;
    $likePost->save();
}

when I click on like button the data insert in the likes table but I want to return the number of the likes in the view also

1

There are 1 best solutions below

2
H H On

In your likePost function, after you've saved the Like then do one of the following:

If you want to return the number of likes the user has:

$likes = Like::where('user_id', Auth::user()->id)->count();

If you want to return the number of likes the ad has:

$likes = Like::where('ad_id', $request->id)->count();

If you want to return the number of all likes:

$likes = Like::count();

Then, as it is an AJAX request, you will need to return a JSON response in your likePost function: https://laravel.com/docs/5.6/responses#json-responses

return response()->json([
    'likes' => $likes
]);

And in your JavaScript, pick up the response like this:

$.ajax({
    url: "{{route('post.like','')}}/"+id,
}).done(function(response) {
    var likes = response.likes; <-- num of likes
});

-- edited --

To show in the view, simply add a class or an id to the html element you want to display the number, for example:

<div id="numberOfLikes"></div>

You can then set it's inner html content using the response you got from AJAX:

$.ajax({
    url: "{{route('post.like','')}}/"+id,
}).done(function(response) {
    var likes = response.likes;
    $('#numberOfLikes').html(response.likes);
});