I have an Excel file with several sheets, each sheet has a specific name and that name is in the "name" column of a product table. I want to make that when I import the Excel file, the name of the sheet in the DB is also imported.
I am using Laravel Excel and PHPOficce packages. And the import is in the laravel console commands.
class ProductImport implements ToCollection, WithHeadingRow, WithProgressBar
{
use Importable;
public function collection(Collection $rows)
{
$reader = IOFactory::createReader('Xlsx');
$reader->setReadDataOnly(TRUE);
$spreadsheet = $reader->load(storage_path('app/fruit/listFruit.xlsx'));
$products = $spreadsheet->getSheetNames();
//name of sheets
//$products=['banana', 'strawberry'];
foreach ($rows as $row) {
foreach ($products as $product) {
ProductImport::updateOrCreate(
[
'price' => $row['price'],
'size' => $row['size'],
'product' => $product,//nameSheet
],
);
}
}
}
}
<?php
namespace App\Console\Commands;
use App\Imports\ProductImport;
use PhpOffice;
use Illuminate\Console\Command;
class UploadProduct extends Command
{
protected $signature = 'fruit:productList';
protected $description = 'Command to inject fruit data';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$this->output->title('Starting import');
(new ProductImport)->withOutput($this->output)->import(storage_path('app/fruit/listFruit.xlsx'));
$this->output->success('Import successful');
}
}
I want that the variable $product every time I go through a sheet, the name of the sheet is imported in the database and that I don't get only the name of the first sheet.