02 — Database
Depends on: 01-requirements.md
Produces: 4 migrations, 4 models
Verify with: php artisan migrate runs clean, then php artisan tinker can create a session
1. Check your existing schema first
These specs assume the columns below. Open your actual migrations and confirm before you run anything — a wrong assumption here breaks every foreign key downstream.
php artisan db:table products
php artisan db:table orders
php artisan db:table order_items
php artisan db:table delivery_zones
Assumed:
| Table | Columns this project uses |
|---|---|
products |
id, name, sku, description, price (decimal), stock (int), is_active |
categories |
id, name, parent_id |
category_product |
category_id, product_id |
orders |
id, order_number, customer_id, status, payment_method, payment_status, subtotal, delivery_fee, total, shipping_name, shipping_phone, shipping_address, delivery_zone_id |
order_items |
id, order_id, product_id, product_name, unit_price, quantity, line_total |
delivery_zones |
id, name, delivery_fee, is_active |
customers |
id, name, phone, email |
If your product table has variants (size, colour as separate rows), stop and adapt — every stock check in these specs assumes one stock number per product.
If your customer table is users not customers, change the foreign key in §2.1.
2. New tables
2.1 whatsapp_sessions
One row per phone number. This is the bot's memory of who it's talking to.
database/migrations/2026_01_01_000001_create_whatsapp_sessions_table.php
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('whatsapp_sessions', function (Blueprint $table) {
$table->id();
// Who we're talking to
$table->string('phone_number', 20)->unique();
$table->string('profile_name', 120)->nullable(); // their WhatsApp display name
$table->foreignId('customer_id')->nullable()->constrained()->nullOnDelete();
$table->foreignId('cart_id')->nullable()->constrained()->nullOnDelete();
// Conversation state
$table->string('state', 32)->default('browsing');
// Details we collect during checkout
$table->string('collected_name', 120)->nullable();
$table->text('delivery_address')->nullable();
$table->foreignId('delivery_zone_id')->nullable()->constrained()->nullOnDelete();
$table->string('payment_method', 32)->nullable();
// Order confirmation (see 04-tools.md §7)
$table->uuid('confirmation_token')->nullable()->unique();
$table->string('confirmation_cart_hash', 64)->nullable();
$table->timestamp('confirmation_issued_at')->nullable();
// WhatsApp 24-hour window
$table->timestamp('last_inbound_at')->nullable();
$table->boolean('needs_human')->default(false);
$table->timestamps();
$table->index(['state', 'last_inbound_at']);
});
}
public function down(): void
{
Schema::dropIfExists('whatsapp_sessions');
}
};
Why confirmation_cart_hash? The token alone isn't enough. If the customer confirms,
then adds an item before the job runs, the token would still be valid for a cart that no
longer matches what they saw. Hashing the cart contents catches that.
2.2 whatsapp_messages
Every message in both directions, plus every tool call and result. This is your conversation history and your debugging log.
database/migrations/2026_01_01_000002_create_whatsapp_messages_table.php
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('whatsapp_messages', function (Blueprint $table) {
$table->id();
$table->foreignId('whatsapp_session_id')->constrained()->cascadeOnDelete();
// WhatsApp's message ID. Unique = our duplicate protection.
// Null for tool calls, which have no WhatsApp ID.
$table->string('wamid', 128)->nullable()->unique();
$table->enum('role', ['user', 'assistant', 'tool']);
$table->enum('direction', ['inbound', 'outbound', 'internal']);
$table->text('body')->nullable();
// Tool calls and results
$table->string('tool_name', 64)->nullable();
$table->string('tool_call_id', 64)->nullable();
$table->json('tool_arguments')->nullable();
$table->json('tool_result')->nullable();
$table->string('status', 16)->nullable(); // sent, delivered, read, failed
$table->timestamps();
$table->index(['whatsapp_session_id', 'id']); // loading history
});
}
public function down(): void
{
Schema::dropIfExists('whatsapp_messages');
}
};
The unique index on wamid is load-bearing. Meta retries webhooks if it doesn't get a
fast 200, and sometimes delivers twice even when it does. Without this index, a retry
means the bot replies twice — or worse, adds to the cart twice. See 03-whatsapp.md §4.
Nullable unique is fine in MySQL: multiple NULLs are allowed, so tool rows coexist.
2.3 carts and cart_items
database/migrations/2026_01_01_000003_create_carts_table.php
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('carts', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->nullable()->constrained()->nullOnDelete();
$table->enum('status', ['active', 'converted', 'expired'])->default('active');
$table->foreignId('converted_order_id')->nullable()->constrained('orders')->nullOnDelete();
$table->timestamp('expires_at')->nullable();
$table->timestamps();
});
Schema::create('cart_items', function (Blueprint $table) {
$table->id();
$table->foreignId('cart_id')->constrained()->cascadeOnDelete();
$table->foreignId('product_id')->constrained()->restrictOnDelete();
$table->unsignedInteger('quantity');
$table->decimal('unit_price_snapshot', 12, 2);
$table->timestamps();
// One row per product per cart
$table->unique(['cart_id', 'product_id']);
});
}
public function down(): void
{
Schema::dropIfExists('cart_items');
Schema::dropIfExists('carts');
}
};
Two things worth understanding here.
unique(['cart_id', 'product_id']) means "add shampoo" twice updates one row instead
of creating two. It turns the add operation into an upsert, which is both simpler to
write and safer on retry.
unit_price_snapshot records what the price was when they added it. This is for
display only — place_order re-reads the live price and refuses if it changed. Never
charge from a snapshot.
2.4 Adding order columns
database/migrations/2026_01_01_000004_add_whatsapp_columns_to_orders.php
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('orders', function (Blueprint $table) {
$table->string('source', 16)->default('web')->after('id');
$table->foreignId('whatsapp_session_id')->nullable()->constrained()->nullOnDelete();
// The confirmation token, stored to prevent duplicate orders
$table->uuid('idempotency_key')->nullable()->unique();
});
}
public function down(): void
{
Schema::table('orders', function (Blueprint $table) {
$table->dropColumn(['source', 'whatsapp_session_id', 'idempotency_key']);
});
}
};
idempotency_key with a unique index is your duplicate-order safety net. If a job
retries and tries to place the same order twice, the second insert hits the unique
constraint and fails. You catch that and return the existing order. See 04-tools.md §7.
3. How it all connects
erDiagram
customers ||--o{ whatsapp_sessions : "may own"
whatsapp_sessions ||--o{ whatsapp_messages : "has"
whatsapp_sessions }o--o| carts : "active cart"
whatsapp_sessions }o--o| delivery_zones : "resolved zone"
carts ||--o{ cart_items : "has"
cart_items }o--|| products : "references"
carts }o--o| orders : "converted to"
orders ||--o{ order_items : "has"
order_items }o--|| products : "references"
products }o--o{ categories : "category_product"
4. Models
app/Models/WhatsAppSession.php
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\PaymentMethod;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class WhatsAppSession extends Model
{
protected $guarded = [];
protected function casts(): array
{
return [
'last_inbound_at' => 'datetime',
'confirmation_issued_at' => 'datetime',
'needs_human' => 'boolean',
'payment_method' => PaymentMethod::class,
];
}
public function cart(): BelongsTo
{
return $this->belongsTo(Cart::class);
}
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
public function deliveryZone(): BelongsTo
{
return $this->belongsTo(DeliveryZone::class);
}
public function messages(): HasMany
{
return $this->hasMany(WhatsAppMessage::class);
}
/** Which checkout details are still missing. */
public function missingForCheckout(): array
{
return collect([
'name' => $this->collected_name,
'delivery_address' => $this->delivery_address,
'payment_method' => $this->payment_method,
])->filter(fn ($value) => blank($value))->keys()->all();
}
/** Any cart or detail change invalidates a pending confirmation. */
public function clearConfirmation(): void
{
$this->update([
'confirmation_token' => null,
'confirmation_cart_hash' => null,
'confirmation_issued_at' => null,
]);
}
}
app/Models/Cart.php
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Cart extends Model
{
protected $guarded = [];
protected function casts(): array
{
return ['expires_at' => 'datetime'];
}
public function items(): HasMany
{
return $this->hasMany(CartItem::class);
}
public function subtotal(): string
{
// bcmath keeps money exact. Never sum floats.
return (string) $this->items->reduce(
fn ($carry, CartItem $item) => bcadd(
$carry,
bcmul((string) $item->unit_price_snapshot, (string) $item->quantity, 2),
2
),
'0.00'
);
}
/**
* Fingerprint of cart contents. Used to detect changes after a
* confirmation token was issued.
*/
public function contentsHash(): string
{
$parts = $this->items
->sortBy('product_id')
->map(fn (CartItem $i) => "{$i->product_id}:{$i->quantity}:{$i->unit_price_snapshot}")
->implode('|');
return hash('sha256', $parts);
}
}
app/Models/CartItem.php
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class CartItem extends Model
{
protected $guarded = [];
protected function casts(): array
{
return ['unit_price_snapshot' => 'decimal:2'];
}
public function cart(): BelongsTo
{
return $this->belongsTo(Cart::class);
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
public function lineTotal(): string
{
return bcmul((string) $this->unit_price_snapshot, (string) $this->quantity, 2);
}
}
app/Models/WhatsAppMessage.php
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class WhatsAppMessage extends Model
{
protected $guarded = [];
protected function casts(): array
{
return [
'tool_arguments' => 'array',
'tool_result' => 'array',
];
}
public function session(): BelongsTo
{
return $this->belongsTo(WhatsAppSession::class, 'whatsapp_session_id');
}
}
5. Product search
Start simple. LIKE is readable, needs no index setup, and performs fine under a few
thousand products.
Product::query()
->where('is_active', true)
->where(function ($q) use ($term) {
$q->where('name', 'like', "%{$term}%")
->orWhere('sku', 'like', "%{$term}%");
})
->limit(10)
->get();
When to upgrade
LIKE '%term%' cannot use an index — MySQL scans every row. That is fine at 2,000
products and slow at 50,000.
The upgrade is a FULLTEXT index:
ALTER TABLE products
ADD FULLTEXT INDEX products_search_ft (name, description) WITH PARSER ngram;
Product::query()
->whereRaw('MATCH(name, description) AGAINST (? IN NATURAL LANGUAGE MODE)', [$term])
->where('is_active', true)
->limit(10)
->get();
Three things to know before you rely on it:
WITH PARSER ngramis required for Bengali. MySQL's default parser splits on spaces and punctuation, which does not work for Bengali script — without ngram, Bengali product names are effectively unsearchable.- No typo tolerance.
shampomatches nothing. Fall back toLIKEwhen FULLTEXT returns zero rows. - Minimum token length defaults to 3, so two-letter brand names are silently unindexed. It's a global MySQL setting requiring a restart, not a per-table one.
Beyond roughly 10,000 products, or if search quality is visibly poor, move to Meilisearch via Laravel Scout. Keep your search in one method so swapping it is a single-file change.
6. Enums
app/Enums/PaymentMethod.php
<?php
declare(strict_types=1);
namespace App\Enums;
enum PaymentMethod: string
{
case CashOnDelivery = 'cash_on_delivery';
case Bkash = 'bkash';
case Nagad = 'nagad';
case Card = 'card';
public function label(): string
{
return match ($this) {
self::CashOnDelivery => 'Cash on Delivery',
self::Bkash => 'bKash',
self::Nagad => 'Nagad',
self::Card => 'Card',
};
}
/** COD is collected at the door; everything else needs follow-up. */
public function initialPaymentStatus(): string
{
return $this === self::CashOnDelivery ? 'pending' : 'awaiting_payment';
}
}
app/Enums/SessionState.php
<?php
declare(strict_types=1);
namespace App\Enums;
enum SessionState: string
{
case Browsing = 'browsing';
case CartActive = 'cart_active';
case AwaitingConfirmation = 'awaiting_confirmation';
case OrderPlaced = 'order_placed';
case HandedOff = 'handed_off';
}
7. Checklist
- [ ] Verified existing table columns against §1
- [ ] Four migrations run clean
- [ ]
php artisan migrate:rollbackalso works - [ ] Models created, relationships load in tinker
- [ ]
$cart->subtotal()returns a correct string for a 2-item cart - [ ]
$session->missingForCheckout()returns all three on a fresh session