Skip to content Skip to sidebar Skip to footer

Laravel - Favourite / Un-favourite Button

I'm trying to create a favourite / un-favourite button for items. The button needs to be toggable so that when the user first clicks it, the item is added to favourites, the next t

Solution 1:

PHP is server side code, so it's completely rendered before it ever leaves the server. That means the other button never exists on the client machine.

You could instead allow both buttons to be sent to the client, but initially hide one from view with CSS.

@foreach($itemsas$item)

    <!-- set color and hide if not favourited -->
    <button id="deletefavourite{{$item->id}}" 
            onClick="deleteFromFavourites({{$item->id}}, {{ Auth::user()->id }})" 
            name="addfavourite"class="btnbtn-lg"
            style="color: #ad1707; {{ $item->isFavourited ? '' : 'display: none;' }}">
        <i class="fas fa-heartbeat"></i>
    </button>

    <!-- hide if favourited -->
    <button id="addfavourites{{$item->id}}" 
            onClick="addToFavourites({{$item->id}}, {{ Auth::user()->id }})" 
            name="deletefavourite" 
            class="btn btn-lg"
            style="{{ $item->isFavourited ? 'display: none;' : '' }}">
        <i class="fas fa-heart" ></i>
    </button>

@endforeach

Then in your JavaScript, you can show or hide the buttons as you make changes.

functionaddToFavourites(itemid, userid) {
    var user_id = userid;
    var item_id = itemid;

    $.ajax({
        type: 'post',
        url: 'api/addfavourite',
        data: {
            'user_id': user_id,
            'item_id': item_id,
        },
        success: function () {
            // hide add button
            $('#addfavourites' + item_id).hide();
            // show delete button
            $('#deletefavourite' + item_id).show();
        },
        error: function (XMLHttpRequest) {
            // handle error
        }
    });
}

// and so on for the other function// ...// show add button
            $('#addfavourites' + item_id).show();
            // hide delete button
            $('#deletefavourite' + item_id).hide();

            // ...

Post a Comment for "Laravel - Favourite / Un-favourite Button"