0

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
souma
  • 9
  • 3

1 Answers1

3

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);
});
H H
  • 2,065
  • 1
  • 24
  • 30
  • i try wihe that but it still insert in the base and dont return a number in the view – souma Apr 27 '18 at 15:43
  • i have edited my answer to show you how to use the `response.likes` from the AJAX to show in your view – H H Apr 30 '18 at 08:47