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.
carts --------- id user_id product_id quantity price created_at updated_at
routes/api.php:
use App\Http\Controllers\Api\CartController;
Route::post('/cart/add', [CartController::class, 'addToCart']);
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'
]);
}
<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>
<button
class="btn btn-primary"
@click="addToCart(product.id)"
>
Add to Cart
</button>