Laravel 10 E-Commerce Project - Removing Products from Wishlist

In this tutorial, we will learn how to remove products from a wishlist.

Let's explore the process of removing products from a wishlist.

Creating a Function in the Wishlist Controller

First, go to the Wishlist Controller and create a function:


public function removeProductFromWishlist(Request $request)
{
$rowId = $request->rowId;
Cart::instance("wishlist")->remove($rowId);
return redirect()->route('wishlist.list');
}

Defining a Route for Removing Products

Next, create a route for this:


Route::delete('/wishlist/remove',[WishlistController::class,'removeProductFromWishlist'])->name('wishlist.remove');

Creating a Form in the Wishlist View

Now, go to the wishlist.blade.php file and create a form:


<form id="deleteFromWishlist" action="{{route('wishlist.remove')}}" method="POST">
@csrf
@method('delete')
<input type="hidden" id="rowId" name="rowId" />
</form>

Creating a JavaScript Function

Create a JavaScript function:


@push('scripts')
<script>
function removeFromWishlist(rowId)
{
$("#rowId").val(rowId);
$("#deleteFromWishlist").submit();
}

</script>
@endpush

Calling the JavaScript Function

Call this function from the remove icon:


<a href="javascript:void(0)" class="icon" onclick="removeFromWishlist('{{$item->rowId}}')">
<i class="fas fa-times"></i>
</a>

Testing the Remove Product Functionality

Now that we've completed the setup, let's test it. Refresh the page and remove a product from the wishlist by clicking the icon. You will see that the product has been removed.

Clearing All Items from the Wishlist

Now, let's make the "Clear all items" link functional.

Creating a Function in the Wishlist Controller

Go to the Wishlist Controller and create a new function:


public function clearWishlist()
{
Cart::instance("wishlist")->destroy();
return redirect()->route('wishlist.list');
}

Defining a Route for Clearing All Items

Create a route for this function:


Route::delete('/wishlist/clear',[WishlistController::class,'clearWishlist'])->name('wishlist.clear');

Creating a Form in the Wishlist View

Go to the wishlist.blade.php file and add a form:


<form id="clearWishlist" action="{{route('wishlist.clear')}}" method="POST">
@csrf
@method('delete')
</form>

Creating a JavaScript Function

Add a JavaScript function:


@push('scripts')
<script>
function clearWishlist()
{
$("#clearWishlist").submit();
}
</script>
@endpush

Calling the JavaScript Function

Call this JavaScript function from the "Clear all items" link on click event:


<div class="row">
<div class="col-md-12 text-end">
<a href="javascript:void(0)" onclick="clearWishlist()">Clear All Items</a>
</div>
</div>

Testing the Clear All Items Functionality

Now that we've completed the setup, let's test it. Refresh the page and click the "Clear all items" link. You will see that all items have been removed from the wishlist.

By following these steps, you can successfully remove products from a wishlist.