Skip to content
Advertisement

Make an asynchronous post request laravel to handle likes?

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!

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement