Laravel 12 Import Products from Woocommerce API
Laravel can easily get products and sync from wordpress woocommerce. Sometimes we have to work in such a project where woocommerce products are needed to fetched and synced in laravel. To do this we can call woocommerce api . Here in this article we will see how to make a laravel syncing feature to fetch products from woocommerce in laravel 12.
1 - Create a Fresh laravel 12 Project
Here we will create a fresh and empty laravel project . You can also make this inside your existing laravel project as well
composer create-project --prefer-dist laravel/laravel laravel-sync 12.*
2 - Create Model
Here we will create a product model along with migration. Here is the command below for creating our Product model along with migration file
php artisan make:model Product -m
Product.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//app/Models/Product.php
/** @use HasFactory<\Database\Factories\ProductFactory> */
use HasFactory;
protected $fillable = [
'name',
'sku',
'price',
'regular_price',
'category',
'brand',
'search_option',
'product_link',
'image',
'status',
];
}Product Table Migration
use App\Helper\Status;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
//database/migrations/2025_03_02_212800_create_products_table.php
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
$table->string('sku')->unique();
$table->double('price')->nullable();
$table->double('regular_price')->nullable();
$table->string('category');
$table->string('brand')->nullable();
$table->string('search_option')->nullable(); // Adjust based on use case
$table->longText('product_link')->nullable();
$table->longText('image_link')->nullable();
$table->tinyInteger('status')->default(Status::STATUS_ACTIVE);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};Now we will start to create a console command and that command will be used to fetch products . Here is command for creating woocommerce products import. This command will create a file inside app/Console/Commands/ImportWooCommerceProducts.php
php artisan make:command ImportWooCommerceProducts
Here is the console command class for importing products from woocommerce website using api
namespace App\Console\Commands;
use App\Models\Product;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class ImportWooCommerceProducts extends Command
{
protected $signature = 'woocommerce:import-products';
protected $description = 'Import all products from WooCommerce into Laravel database';
/**
*/
public function handle()
{
$consumerKey = env('WC_CONSUMER_KEY');
$consumerSecret = env('WC_CONSUMER_SECRET');
$storeUrl = env('WC_STORE_URL');
$perPage = 50; // Number of products per request
$page = 1;
$totalPages = 1;
try {
Log::channel('woocommerce_import_log')->info('Import process started.');
do {
// Fetch products from WooCommerce
$response = Http::withOptions([
'verify' => false,
])->withBasicAuth($consumerKey, $consumerSecret)
->get("$storeUrl/wp-json/wc/v3/products", [
'per_page' => $perPage,
'page' => $page
]);
if ($response->failed()) {
$this->error('Failed to fetch WooCommerce products.');
Log::channel('woocommerce_import_log')->info('WooCommerce failed to connect to WooCommerce.', [
'message' => $response->getBody()->getContents(),
'consumerKey' => env('WC_CONSUMER_KEY'),
'consumerSecret' => env('WC_CONSUMER_SECRET'),
'storeUrl' => env('WC_STORE_URL'),
]);
return;
}
Log::channel('woocommerce_import_log')->info('Woocommerce api connection successful', ['status' => $response->getStatusCode()]);
$products = $response->json();
$totalPages = $response->header('X-WP-TotalPages', 1);
$categoryName = isset($product['categories'][0]) ? $product['categories'][0]['name'] : 'Uncategorized';
$brandName = 'Unknown';
$imageUrl = null;
foreach ($products as $product) {
if (isset($product['attributes'])) { //take brand from attributes
foreach ($product['attributes'] as $attribute) {
if (strtolower($attribute['slug']) == 'pa_cosmetics-brands' && !empty($attribute['options'])) {
$brandName = $attribute['options'][0]; // Take the first brand option
break;
}
}
}
$this->insertProductIntoDatabase($product, $categoryName, $brandName);
// Log each product import
Log::channel('woocommerce_import_log')->info('Imported product', [
'sku' => $product['sku'],
'product_name' => $product['name'],
]);
}
$this->info("Imported page $page of WooCommerce products.");
$page++;
} while ($page <= $totalPages);
$this->info('WooCommerce product import completed.');
Log::channel('woocommerce_import_log')->info('WooCommerce product import completed.');
} catch (\Exception $e) {
$this->info('WooCommerce product import failed');
Log::channel('woocommerce_import_log')->info('WooCommerce product import failed', [
'consumerKey' => env('WC_CONSUMER_KEY'),
'consumerSecret' => env('WC_CONSUMER_SECRET'),
'storeUrl' => env('WC_STORE_URL'),
'line' => $e->getLine(),
'message' => $e->getMessage(),
]);
}
}
/**
* @param mixed $product
* @param mixed $categoryName
* @param mixed $brandName
* @return void
*/
private function insertProductIntoDatabase(mixed $product, mixed $categoryName, mixed $brandName): void
{
Product::updateOrCreate(
['sku' => $product['sku']], // Check by WooCommerce sku
[
'name' => $product['name'],
'sku' => $product['sku'] ?? null,
'category' => $categoryName,
'brand' => $brandName,
'price' => (double)$product['price'] ?? null,
'regular_price' => (double)$product['regular_price'] ?? null,
'product_link' => $product['permalink'],
]
);
}
}We will have to add three environment variable value inside .env file as we have used inside our class
WC_CONSUMER_KEY=ck_a3c29855b59454d18xxxxxxx WC_CONSUMER_SECRET=cs_043e0e0494d057b9f34fxxxxxxxxxxx WC_STORE_URL=https://example.com
Now run command from terminal and it will start importing products from woocommerce .
php artisan woocommerce:import-products
You can also add this command in schedular. This schedular will be run in background. Open your bootstrap/app.php file and modify your Application configuration like below one
->withSchedule(function (Schedule $schedule) {
$schedule->command('woocommerce:import-products')->daily();
})->create();