Backend DevelopmentFrontend Development

Building a Book Selling Website with Laravel and Nuxt.js 3: Part 3

Building a Book Selling Website with Laravel and Nuxt 3

In the previous parts of the series “Building a Book Selling website with laravel and Nuxt.js 3” we implemented the book catalog, categories, book listings, search, and book details. It’s time to add the basic e-commerce functionality that allows customers to purchase books.

 

 

 

What will we build in this part?

  • Add books to their shopping cart.
  • View their cart and update book quantities.
  • Remove books from their cart.

We will not persist the cart state into Database, instead we will use localStorage, but if a real world project it’s important to persist the cart into Database.

Database Tables

We will need these tables for orders:

  • orders: Stores customer and order information.
  • order_items: Stores the books included in each order.

 

Creating the Laravel migrations

Create these models and migrations:

php artisan make:model Order -m

php artisan make:model OrderItem -m

Open then generated migration:

database/migrations/xxx_create_orders_table.php

public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->string('customer_name');
            $table->string('email');
            $table->string('phone');
            $table->text('address');
            $table->decimal('total', 10, 2);
            $table->string('status')->default('pending');
            $table->timestamps();
        });
    }

Order status can be:

  • pending: The order has been placed and is awaiting processing.
  • processing: The order is being prepared.
  • completed: The order has been delivered.
  • cancelled: The order has been cancelled.

We will initially create every order with the pending status.

 

Open:

database/migrations/xxx_create_order_items_table.php

public function up(): void
    {
        Schema::create('order_items', function (Blueprint $table) {
            $table->id();

            $table->foreignId('order_id')
                ->constrained()
                ->cascadeOnDelete();

            $table->foreignId('book_id')
                ->nullable()
                ->constrained()
                ->nullOnDelete();

            $table->string('book_title');

            $table->unsignedInteger('quantity');

            $table->decimal('price', 10, 2);

            $table->timestamps();
        });
    }

The book_id is nullable because we want to preserve historical order information even if a book is deleted later.

The book_title and price fields act as snapshots of the purchased book information.

Run the migrations:

php artisan migrate

 

Eloquent Models and Relationships

Order Model:

Open app/Models/Order.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[Fillable('customer_name', 'email', 'phone', 'address', 'total', 'status')]
class Order extends Model
{
    protected function casts(): array
    {
        return [
          'total' => 'decimal:2'
        ];
    }

    public function items() : HasMany
    {
        return $this->hasMany(OrderItem::class);
    }
}

 

OrderItem Model:

Open app/Models/OrderItem.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

#[Fillable('order_id', 'book_id', 'quantity', 'price', 'book_title')]
class OrderItem extends Model
{
    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class);
    }

    public function book(): BelongsTo
    {
        return $this->belongsTo(Book::class);
    }
}

 

Implementing Order Creation in Laravel

We need an API endpoint that accepts customer information and the selected books, validates stock, calculates the total, and creates the order.

The frontend will send something similar to this:

{
    "customer_name": "John Smith",
    "email": "john@example.com",
    "phone": "123456789",
    "address": "Cairo, Egypt",
    "items": [
        {
            "book_id": 1,
            "quantity": 2
        },
        {
            "book_id": 3,
            "quantity": 1
        }
    ]
}

Notice that we are not sending book prices or order totals. We will retrieve these values from the database.

 

Create the OrderController

php artisan make:controller Api/OrderController

Open OrderController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Book;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class OrderController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255'],
            'phone' => ['required', 'string', 'max:30'],
            'address' => ['required', 'string', 'max:1000'],

            'items' => ['required', 'array', 'min:1'],
            'items.*.book_id' => [
                'required',
                'integer',
                'distinct',
                'exists:books,id',
            ],
            'items.*.quantity' => [
                'required',
                'integer',
                'min:1',
                'max:20',
            ],
        ]);

        $order = DB::transaction(function () use ($validated) {
            $orderItems = [];
            $total = 0;

            // Lock and retrieve the selected books.
            $items = collect($validated['items'])
                ->sortBy('book_id');

            foreach ($items as $item) {
                $book = Book::whereKey($item['book_id'])
                    ->lockForUpdate()
                    ->firstOrFail();

                if ($book->stock < $item['quantity']) {
                    throw ValidationException::withMessages([
                        'items' => [
                            "Insufficient stock for {$book->title}."
                        ],
                    ]);
                }

                $priceInCents = (int) round(
                    (float) $book->price * 100
                );

                $lineTotal = $priceInCents * $item['quantity'];

                $total += $lineTotal;

                $orderItems[] = [
                    'book' => $book,
                    'quantity' => $item['quantity'],
                ];
            }

            // Create the order.
            $order = Order::create([
                'customer_name' => $validated['customer_name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'],
                'address' => $validated['address'],
                'total' => number_format($total / 100, 2, '.', ''),
                'status' => 'pending',
            ]);

            // Create order items and update stock.
            foreach ($orderItems as $item) {

                $book = $item['book'];
                $quantity = $item['quantity'];

                $order->items()->create([
                    'book_id' => $book->id,
                    'book_title' => $book->title,
                    'quantity' => $quantity,
                    'price' => $book->price,
                ]);

                $book->decrement('stock', $quantity);
            }

            return $order;

        });

        return response()->json([
            'message' => 'Order placed successfully.',
            'order' => $order->load('items'),
        ], 201);
    }
}

Let’s understand the order creation flow:

  • Validate customer information and cart items: We validate the customer details and ensure that the cart contains at least one book. 
  • Retrieve the actual book prices: We retrieve each book from the database.
  • Check stock availability: We make sure the requested quantity does not exceed the available stock.
  • Use a database transaction: We wrap the entire process in DB::transaction(). This means that if anything fails while creating the order or updating stock, Laravel rolls back the entire transaction.
  • We also use lockForUpdate() to prevent concurrent checkout requests from purchasing the same available stock.
  • Create the order and order items: We store the original book price in title in the order items, then reduce the available stock.

 

Register the order API route

Open routes/api.php and add:

use App\Http\Controllers\Api\OrderController;

Route::controller(OrderController::class)->group(function () {
    Route::post('/orders', 'store');
});

Our backend order creation endpoint is now ready:

POST /api/orders

 

Implementing the shopping cart in Nuxt 3

As mentioned earlier, we will store the shopping cart in the browser using localStorage.

Our cart will contain only:

  • Book ID.
  • Book title.
  • Book slug.
  • Book price.
  • Book cover.
  • Selected quantity.

We will not create any cart related-db tables.

 

Create a cart composable

Create:

composables/useCart.ts

import type {CartItem} from "~/inc/types.ts";

const cart = ref<CartItem[]>([]);

export const useCart = () => {
    function addToCart(book: any) {
        const existing = cart.value.find(
            item => item.book_id === book.id
        )

        if (existing) {
            existing.quantity++
        } else {
            cart.value.push({
                book_id: book.id,
                title: book.title,
                slug: book.slug,
                price: Number(book.price),
                cover_image: book.cover_image,
                quantity: 1,
            })
        }

        updateLocalStorage();
    }

    function updateQuantity(bookId: number, quantity: number) {
        const item = cart.value.find(
            item => item.book_id === bookId
        )

        if (item && quantity >= 1) {
            item.quantity = quantity
        }

        updateLocalStorage();
    }

    function removeFromCart(bookId: number) {
        cart.value = cart.value.filter(
            item => item.book_id !== bookId
        )

        updateLocalStorage();
    }

    function clearCart() {
        cart.value = [];

        updateLocalStorage();
    }

    const cartCount = computed(() =>
        cart.value.reduce(
            (total, item) => total + item.quantity,
            0
        )
    )

    const cartTotal = computed(() =>
        cart.value.reduce(
            (total, item) => total + item.price * item.quantity,
            0
        )
    )

    const updateLocalStorage = () => {
        localStorage.setItem('bookstore_cart', JSON.stringify(cart.value))
    }

    onMounted(() => {
        const savedCart = localStorage.getItem('bookstore_cart')
        if (savedCart) {
            cart.value = JSON.parse(savedCart)
        }
    })

    return {
        cart,
        cartCount,
        cartTotal,
        addToCart,
        updateQuantity,
        removeFromCart,
        clearCart,
    }
}

This composable wraps the necessary cart handling persistence and operations. The cart ref declared outside of the composable to be shared globally through the whole app, otherwise it will loss the reactive state when updating cart.

Add the CartItem type interface to the app/inc/types.ts

export interface CartItem {
    book_id: number
    title: string
    slug: string
    price: number
    cover_image: string | null
    quantity: number
}

 

Add a shopping cart link to the header

Update our existing layouts/default.vue

<script setup lang="ts">
const { cartCount } = useCart()
</script>

<template>
  <div>
    <header class="bg-white shadow-sm">
      <nav class="container mx-auto px-4 py-5 flex justify-between">
        <NuxtLink to="/" class="text-2xl font-bold text-indigo-700">
          BookStore
        </NuxtLink>

        <div class="flex gap-6">
          <NuxtLink to="/">Home</NuxtLink>
          <NuxtLink to="/books">Books</NuxtLink>
          <NuxtLink to="/cart">
            Cart ({{ cartCount }})
          </NuxtLink>
        </div>
      </nav>
    </header>

    <main class="container mx-auto px-4 py-8">
      <slot />
    </main>
  </div>
</template>

Now customers can see their cart item count from any page, and when adding to the cart the header cart will refresh instantly.

 

Add the “Add to Cart” button to book details

Open

pages/books/[slug].vue

Inside the script section add:

const {addToCart} = useCart();

function handleAddToCart() {
  addToCart(book.value);

  alert("Book added to cart!");

  // Handle redirect to cart page 
}

Replace the disabled button with:

<button
  :disabled="book.stock < 1"
  @click="handleAddToCart()"
  class="bg-indigo-700 text-white px-8 py-3 rounded-lg
         disabled:opacity-50 disabled:cursor-not-allowed"
>
  {{ book.stock > 0 ? 'Add to Cart' : 'Out of Stock' }}
</button>

That’s all we need to add books to the cart.

The stock displayed on the product page is only informational, the backend will perform the authoritative stock check during checkout.

 

Create the shopping cart page

Create:

pages/cart.vue

<script setup lang="ts">
const {
  cart,
  cartTotal,
  updateQuantity,
  removeFromCart
} = useCart()

const loading = ref(true);

onMounted(() => {
  loading.value = false;
})

</script>

<template>
  <div>
    <h1 class="text-3xl font-bold mb-3">
      Shopping Cart
    </h1>

    <div v-if="loading" class="text-center py-16">
      <p class="text-gray-500 mb-5">
        Loading...
      </p>

    </div>

    <div v-else-if="cart.length === 0 && !loading" class="text-center py-16">
      <p class="text-gray-500 mb-5">
        Your shopping cart is empty.
      </p>

      <NuxtLink
          to="/books"
          class="bg-indigo-700 text-white px-6 py-3 rounded-lg"
      >
        Browse Books
      </NuxtLink>
    </div>

    <div v-else class="grid grid-cols-2 lg:grid-cols-3 gap-3">

      <!-- Cart Items -->
      <div class="lg:col-span-2 space-y-4">

        <div
            v-for="item in cart"
            :key="item.book_id"
            class="flex gap-4 border rounded-lg p-4"
        >
          <img
              v-if="item.cover_image"
              :src="item.cover_image"
              class="w-20 h-28 object-cover rounded"
          />

          <div
              v-else
              class="w-20 h-28 bg-gray-100 rounded"
          />

          <div class="flex-1">
            <NuxtLink
                :to="`/books/${item.slug}`"
                class="font-semibold text-lg"
            >
              {{ item.title }}
            </NuxtLink>

            <p class="text-indigo-700 font-bold mt-2">
              ${{ item.price.toFixed(2) }}
            </p>

            <div class="flex items-center gap-3 mt-3">
              <input
                  type="number"
                  min="1"
                  max="20"
                  :value="item.quantity"
                  @change="updateQuantity(
                  item.book_id,
                  Math.min(20, Math.max(1, Number(($event.target as HTMLInputElement).value) || 1))
                )"
                  class="border rounded w-16 px-2 py-1"
              />

              <button
                  @click="removeFromCart(item.book_id)"
                  class="text-red-600 text-sm"
              >
                Remove
              </button>
            </div>
          </div>

          <div class="font-semibold">
            ${{ (item.price * item.quantity).toFixed(2) }}
          </div>
        </div>

      </div>

      <!-- Cart Summary -->
      <div class="border rounded-lg px-5 py-3 h-fit">
        <h2 class="text-xl font-bold mb-5">
          Order Summary
        </h2>

        <div class="flex justify-between mb-4">
          <span>Subtotal</span>

          <span class="font-bold">
            ${{ cartTotal.toFixed(2) }}
          </span>
        </div>

        <p class="text-sm text-gray-500 mb-5">
          Shipping costs will be confirmed when placing your order.
        </p>

        <NuxtLink
            to="/checkout"
            class="block text-center bg-indigo-700 text-white
                 py-3 rounded-lg"
        >
          Proceed to Checkout
        </NuxtLink>
      </div>

    </div>
  </div>
</template>

We now have a working shopping cart with quantity updates and item removal.

Notice that the cart subtotal is calculated on the frontend only for display. Laravel will calculate the actual total during checkout.

Update the book details the add to cart handler handleAddToCart() to navigate to the cart page:

function handleAddToCart() {
  addToCart(book.value);

  alert("Book added to cart!");

  navigateTo('/cart');
}

 

Continue to part 4: Cart Checkout

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted