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 Tutorial API Based

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

 In this tutorial, you’ll learn how to add products to a shopping cart using Laravel & Vue.js 3 with an API based approach.This follows the same CRUD pattern as Product Create, Update, and Delete—perfect for Ecommerce and SPA projects. 

Step One : Database Structure

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

Step Two : Laravel API Route

routes/api.php:

use App\Http\Controllers\Api\CartController;

Route::post('/cart/add', [CartController::class, 'addToCart']);

Step Three : CartController – Add to Cart

app/Http/Controllers/Api/CartController.php:

public function addToCart(Request $request)
{
    $request->validate([
        'product_id' => 'required|exists:products,id',
        'quantity' => 'required|integer|min:1',
    ]);

    $cart = Cart::where('user_id', auth()->id())
        ->where('product_id', $request->product_id)
        ->first();

    if ($cart) {
        $cart->quantity += $request->quantity;
        $cart->save();
    } else {
        Cart::create([
            'user_id' => auth()->id(),
            'product_id' => $request->product_id,
            'quantity' => $request->quantity,
            'price' => Product::find($request->product_id)->price,
        ]);
    }

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

Step Four : Vue.js 3 Add to Cart Method

<script setup>
import axios from 'axios'

const addToCart = async (productId) => {
    try {
        const res = await axios.post(
            'http://127.0.0.1:8000/api/cart/add',
            {
                product_id: productId,
                quantity: 1
            }
        )

        alert(res.data.message)
    } catch (error) {
        alert('Failed to add product to cart')
    }
}
</script>

Step Five : Add to Cart Button

<button
    class="btn btn-primary"
    @click="addToCart(product.id)"
>
    Add to Cart
</button>

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!