Commerce: Checkout and Order Processing – Housekeeping 🧹
This section covers the ClearExpiredCheckoutSessions artisan command. It periodically cleans up stale checkout sessions and shopping cart entries older than 24 hours to ensure the commerce subsystem remains performant and storage-efficient.
Command Overview
- Signature:
app:clear-expired-checkout-sessions - Description: Clears expired checkout sessions and cart data older than 24 hours
- Location:
app/Console/Commands/ClearExpiredCheckoutSessions.php
Purpose and Responsibilities
- Remove outdated checkout_data entries to free up database space.
- Purge stale shoppingcart rows to prevent cart bloat.
- Wraps deletions in a database transaction for atomicity.
- Logs success or failure messages to the console.
Implementation Details
Handle Method Walkthrough
public function handle(): int
{
try {
DB::beginTransaction();
// Delete checkout sessions older than 24 hours
$checkoutRecordsDeleted = DB::table('checkout_data')
->where('created_at', '<', now()->subHours(24))
->delete();
// Delete shopping cart entries older than 24 hours
$cartRecordsDeleted = DB::table('shoppingcart')
->where('created_at', '<', now()->subHours(24))
->delete();
DB::commit();
$this->info("Successfully deleted
{$checkoutRecordsDeleted} checkout sessions and {$cartRecordsDeleted} cart records.");
return Command::SUCCESS;
} catch (\Exception $e) {
DB::rollBack();
$this->error("Failed to delete expired sessions: {$e->getMessage()}");
return Command::FAILURE;
}
}
Key points:
- Uses
now()->subHours(24)to define the expiration threshold. - Wraps operations in
DB::beginTransaction()/DB::commit()/DB::rollBack(). - Reports counts of deleted records for monitoring.
Affected Database Tables
The command operates on two tables created by migrations:
| Table Name | Columns | Description |
|---|---|---|
| checkout_data | id, identifier, data, created_at, updated_at |
Stores raw checkout session payloads (Stripe data). |
| shoppingcart | identifier, instance, content, created_at, updated_at |
Stores serialized cart contents per session. |
Migrations that define these tables:
Configuration for the shoppingcart table name is defined in config/cart.php:
'database' => [
'connection' => env('DB_CONNECTION', 'mysql'),
'table' => 'shoppingcart',
],
Scheduling and Execution
The command is scheduled to run daily at 01:00 via the application scheduler:
Schedule::command('app:clear-expired-checkout-sessions')->dailyAt('1:00');
To run manually:
php artisan app:clear-expired-checkout-sessions
Best Practices and Tips
{
"title": "Monitor Deletions",
"content": "Review deleted record counts in logs to spot abnormal patterns."
}
- Consistency: Keep the 24-hour retention aligned with Stripe’s session validity.
- Safety: The transaction ensures partial failures do not leave the database in an inconsistent state.
- Performance: Regular cleanup prevents table growth and keeps queries on these tables efficient.