<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Wipes all products and their directly-owned catalog data — for clearing
* out demo/test products (e.g. DemoDataSeeder's 8 sample items) or a
* previous partial import before re-running ImportChandraPharmaProducts.
*
* Deliberately leaves categories, brands, vendors, and orders/reviews
* alone — this only clears the product rows and the tables that exist
* purely to describe a product (images, variants, inventory, the
* product_category pivot). If you have real orders referencing these
* products, deleting them first will violate FK constraints on purpose —
* that's a signal to stop, not something to force through.
*
* Usage:
* php artisan products:clear (asks for confirmation)
* php artisan products:clear --force (skips confirmation)
*/
class ClearProductsCommand extends Command
{
protected $signature = 'products:clear {--force : Skip the confirmation prompt}';
protected $description = 'Delete all products and their related catalog data (images, variants, inventory, category links)';
public function handle(): int
{
$productCount = DB::table('products')->count();
if ($productCount === 0) {
$this->info('No products to clear.');
return self::SUCCESS;
}
if (! $this->option('force') && ! $this->confirm("This will permanently delete all {$productCount} product(s) and their images/variants/inventory. Continue?")) {
$this->warn('Cancelled — nothing was deleted.');
return self::SUCCESS;
}
Schema::disableForeignKeyConstraints();
foreach ([
'inventory_movements',
'inventory',
'product_images',
'product_variants',
'product_category',
'products',
] as $table) {
DB::table($table)->truncate();
}
Schema::enableForeignKeyConstraints();
$this->info("Cleared {$productCount} product(s) and their related rows. Categories, brands, and vendors were left untouched.");
return self::SUCCESS;
}
}