Laravel 12 E-Commerce: Move Product From Wishlist to Cart (Part 30)
This tutorial covers implementing the functionality to move a product from the Wishlist to the Shopping Cart using the WishlistController.
1. Create `move_to_cart` Function in `WishlistController`
The move_to_cart function in `WishlistController.php` retrieves the item from the "wishlist" instance, removes it, and then adds it to the "cart" instance with a quantity of 1.
`WishlistController.php` - `move_to_cart` function
public function move_to_cart($rowId)
{
$item = Cart::instance("wishlist")->get($rowId);
Cart::instance("wishlist")->remove($rowId);
Cart::instance("cart")->add($item->id,$item->name,1,$item->price)->associate("App\Models\Product");
return redirect()->back();
}
2. Define Route for Moving to Cart
Define a POST route in `web.php` to handle the request for moving a product from the wishlist to the cart.
Route in `web.php`
Route::post("/wishlist/move-to-cart/{rowId}",[WishlistController::class,"move_to_cart"])->name("wishlist.move.to.cart’);
3. Update `wishlist.blade.php` for "Move to Cart" Button
Add the form for the "Move to Cart" button in your `wishlist.blade.php` view, along with the form for removing the product from the wishlist.
`wishlist.blade.php` - Action Forms
<td class="product-add-to-cart">
<form method="POST" action="{{route("wishlist.move.to.cart", ["rowId" => $item->rowId])}}">
@csrf
<button type="submit" class="btn btn-dark btn-hover-primary">Move to Cart</button>
</form>
</td>
<td class="product-action">
<form method="POST" action="{{route("wishlist.item.remove", ["rowId" => $item->rowId])}}" id="remove-item-{{$item->id}}">
@csrf
@method("DELETE")
<button class="remove" type="submit">
<i class="pe-7s-trash"></i>
</button>
</form>
</td>
This completes the functionality for moving a product from the wishlist to the shopping cart.
