Loading...
+880 1736 699819 Mon - Sat: 9:00 AM - 8:00 PM
Follow us:
Home Blog Article
Blog

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>

Tags: Blog
Share this post

Encoderbase Team

Author

Articles and insights from the Encoderbase editorial team covering web development, software engineering, and digital solutions.

Enjoyed this article?

Get more articles like this delivered to your inbox — no spam, unsubscribe any time.

Link copied to clipboard!