Laravel 10 E-Commerce Project - Moving Products from Wishlist to Cart

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

Let's explore the process of moving products from a wishlist to a cart.

Creating a Function in the Wishlist Controller

First, go to the WishlistController and create a function:


public function moveToCart(Request $request)
{
$item = Cart::instance('wishlist')->get($request->rowId);
Cart::instance('wishlist')->remove($request->rowId);
Cart::instance('cart')->add($item->model->id, $item->model->name, 1, $item->model->regular_price)->associate('App\Models\Product');
return redirect()->route('wishlist.list');
}

Defining a Route for Moving Products

Next, create a route for this function:


Route::post('/wishlist/move-to-cart',[WishlistController::class,'moveToCart'])->name('wishlist.move.to.cart');

Creating a Form in the Wishlist View

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


<form id="moveToCart" action="{{route('wishlist.move.to.cart')}}" method="POST">
@csrf
<input type="hidden" name="rowId" id="mrowId" />
</form>

Creating a JavaScript Function

Create a JavaScript function:


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

</script>
@endpush

Calling the moveToCart Function

Call this moveToCart function from here:


<td>
@if($item->model->stock_status == 'instock')
<a href="javascript:void(0)" class="icon" onclick="moveToCart('{{$item->rowId}}')">
<i class="fas fa-shopping-cart"></i>
</a>
@else
<a href="javascript:void(0)" class="icon disabled">
<i class="fas fa-shopping-cart"></i>
</a>
@endif
<a href="javascript:void(0)" class="icon" onclick="removeFromWishlist('{{$item->rowId}}')">
<i class="fas fa-times"></i>
</a>
</td>

Testing the Move to Cart Functionality

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

Check the cart by clicking the cart link, and you will see that the product has been successfully added.

By following these steps, you can successfully move products from a wishlist to a cart.