Home > Blockchain >  Make an asynchronous post request laravel to handle likes?
Make an asynchronous post request laravel to handle likes?

Time:07-22

Currently I am handling likes like so:

    class LikeController extends Controller
    {
        public function like(Post $post)
        {

            $attributes = [
                ['user_id', '=', auth()->user()->id],
                ['post_id', '=', $post->id]
            ];

            $like = Like::where($attributes);

            if($like->exists()) {
                $like->delete();

            } else {
                Like::create(['user_id' => auth()->user()->id, 'post_id' => $post->id]);
            }

            return redirect()->to(url()->previous());

        }
    }

and I have a route:

    Route::post('like/{post}', [LikeController::class, 'like']);

What I don't like is that each time a like is clicked a new request is sent and the page refreshes to the top, so I added this javascript to scroll back to the previous position when a like is clicked:

    $(window).on("scroll", function(e) {
        $.cookie("tempScrollTop", $(window).scrollTop());
    });
    
    $(".like-form").each(function() {
        $(this).submit(function(e) {
            $.cookie("action", 'like', {path: '/'});
        })
    });
    
    $(window).on("load", function (e) {
        if ($.cookie("tempScrollTop") && $.cookie('action') === 'like') {
            $(window).scrollTop($.cookie("tempScrollTop"));
            $.cookie("action", '', {path: '/'});
        }
    })


This all works great, but I still don't like seeing the page refresh when hitting a like button. Is there a way to make the post request async and/or let it run in the background such that when hitting the like button the page doesn't refresh but the like does get sent to the server? What would be otherwise the correct method to achieve this result?

Thank you any help will be appreciated!

CodePudding user response:

You can do Ajax request via jQuery, or you can use Livewire.

Here is a good blog how to make Livewire Like button: https://rappasoft.com/blog/building-a-like-button-component-in-laravel-livewire

CodePudding user response:

You should'nt use a redirection in your api, but instead implement an ajax request that just return a success message.

        public function like(Post $post)
        {

            // ...

            return response()->json("Post successfuly liked"); // Or you could return the Post, or Like object if you want.

        }

On the front end side, when calling that route you could then handle the response, for example incrementing the counter :

    $(".like-form").each(function() {
        $(this).submit(function(event) {
            // call the api here, and then handle the response through a callback
            // ex: 
            fetch(`${API_URL}/post/like`).then(response => 
                // do something, like querying the dom element for its value and incrementing it.
            )
        });
    });
  • Related