Laravel & Vue.js 3 Product Add to Cart – Get & Delete Tutorial API Based

Laravel & Vue.js 3 Product Add to Cart – Get & Delete Tutorial API Based

 In this tutorial, you’ll learn how to fetch cart products and remove items from the cart using Laravel & Vue.js 3 (API based).

Step One : Cart Table Structure

carts
---------
id
user_id
product_id
quantity
price
created_at
updated_at

Step Two : Laravel API Routes (Get & Delete)

routes/api.php:

use App\Http\Controllers\Api\CartController;

Route::get('/cart', [CartController::class, 'index']);
Route::delete('/cart/{id}', [CartController::class, 'destroy']);

Step Three : Laravel CartController

public function index()
{
    $cartItems = Cart::with('product')
        ->where('user_id', auth()->id())
        ->get();

    return response()->json([
        'status' => true,
        'data' => $cartItems
    ], 200);
}
public function destroy($id)
{
    $cart = Cart::where('id', $id)
        ->where('user_id', auth()->id())
        ->first();

    if (!$cart) {
        return response()->json([
            'status' => false,
            'message' => 'Cart item not found'
        ], 404);
    }

    $cart->delete();

    return response()->json([
        'status' => true,
        'message' => 'Product removed from cart successfully'
    ], 200);
}

Step Four : Vue.js 3 – Get Cart Products

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const cartItems = ref([])

const fetchCart = async () => {
    const res = await axios.get('http://127.0.0.1:8000/api/cart')
    cartItems.value = res.data.data
}

onMounted(fetchCart)
</script>

Step Five : Display Cart Products

<div v-for="item in cartItems" :key="item.id" class="cart-item">
    <p>{{ item.product.name }}</p>
    <p>Price: {{ item.product.price }}</p>
    <p>Qty: {{ item.quantity }}</p>

    <button @click="removeCartItem(item.id)">
        Remove
    </button>
</div>

Step Six : Vue.js 3 – Delete Cart Product

<script setup>
const removeCartItem = async (id) => {
    if (!confirm('Remove product from cart?')) return

    await axios.delete(
        `http://127.0.0.1:8000/api/cart/${id}`
    )

    fetchCart()
}
</script>