Skip to content

Instantly share code, notes, and snippets.

@dmaksimov
Created January 28, 2022 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmaksimov/10757eccbc6a92934e594074f99b9842 to your computer and use it in GitHub Desktop.
Save dmaksimov/10757eccbc6a92934e594074f99b9842 to your computer and use it in GitHub Desktop.
<?php
namespace App\Console\Commands;
use App\Models\Product;
use App\Models\ProductVariant;
use Illuminate\Console\Command;
class FindProductDuplicates extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'find-product-duplicates';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// Find duplicates
$products = Product::orderBy('id')->get();
foreach ($products as $product) {
if ($duplicateProduct = $this->findDuplicate($product)) {
if ($duplicateProduct->title != $product->title) {
$this->info($product->title . '(#'.$product->id.')' . ' :: ' . $duplicateProduct->title . '(#'.$duplicateProduct->id.')');
}
}
}
return 0;
}
protected function findDuplicate($product)
{
if ($product->uses_variants) {
foreach ($product->variants as $variant) {
if (empty($variant->sku)) {
continue;
}
$duplicateVariant = ProductVariant::where('product_id', '!=', $product->id)
->where('sku', $variant->sku)
->first();
if ($duplicateVariant) {
return $duplicateVariant->product;
}
}
} else {
if (! empty($product->sku)) {
$duplicateProduct = Product::where('id', '!=', $product->id)
->where('sku', $product->sku)
->first();
if ($duplicateProduct) {
return $duplicateProduct;
}
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment