Skip to content

Cart Model

Shopping cart for users and guest sessions.

Overview

The Cart model represents a shopping cart for both authenticated users and guest sessions. It supports multi-tenancy, prescription management, and advanced cart operations.

Attributes

AttributeTypeDescription
idintPrimary key
uuidstringUnique identifier for routing
user_idintForeign key to User (nullable)
carrier_idintForeign key to Carrier
member_idintForeign key to Member (nullable)
session_idstringGuest session identifier (nullable)
statusstringCart status (active, completed, abandoned)
expires_attimestampCart expiration timestamp
created_attimestampCreation timestamp
updated_attimestampLast update timestamp

Relationships

Belongs To

  • belongsTo(User) - Associated user
  • belongsTo(Carrier) - Associated carrier
  • belongsTo(Member) - Associated member

Has Many

  • hasMany(CartItem) - Cart items

Key Features

Multi-Tenancy

  • Associated with a specific carrier
  • Supports both user and guest carts

Cart Management

  • Add, remove, update, and clear items
  • Cart expiration and status management
  • Guest to user cart conversion

Prescription Management

  • Detects prescription items
  • Tracks prescription status for each item

Price & Inventory

  • Total calculations and formatting
  • Inventory checks on add/update

Routing & UUIDs

  • UUID-based routing for security
  • Route key using UUID

Usage Examples

Creating a Cart

php
$cart = Cart::create([
    'uuid' => Str::uuid(),
    'user_id' => $user->id,
    'carrier_id' => $carrier->id,
    'status' => 'active',
    'expires_at' => now()->addDays(7)
]);

Adding Items

php
$cart->addItem($product, 2);

Removing Items

php
$cart->removeItem($product);

Updating Quantity

php
$cart->updateQuantity($product, 5);

Clearing the Cart

php
$cart->clear();

Getting Cart Items

php
$items = $cart->cartItems;

Calculating Totals

php
$total = $cart->total;
$formattedTotal = $cart->formatted_total;

Scopes

Active Carts

php
Cart::where('status', 'active')->get();

Non-Expired Carts

php
Cart::where('expires_at', '>', now())->get();

Route Key

The Cart model uses the uuid as the route key for secure routing:

php
// Route model binding uses UUID
Route::get('/carts/{cart}', function (Cart $cart) {
    return $cart;
});