I solved like that:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\OperationImport;
class OperationImportJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $file;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($file)
{
$this->file = $file;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Excel::import(new OperationImport(), $this->file);
echo "Import finished.";
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function import(Request $request)
{
$file = $request->file('import');
$file = $request->file('import')->store('temp');
$path = storage_path('app') . '/' . $file;
dispatch(new OperationImportJob($path));
return back()->withStatus(__('Operations successfully queued and will be imported soon.'));
}
<?php
namespace App\Imports;
use App\Operation;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class OperationSheetImport implements ToCollection, WithHeadingRow, WithChunkReading
{
public function headingRow(): int
{
return 5;
}
/**
* Transform a date value into a Carbon object.
*
* @return \Carbon\Carbon|null
*/
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromDate($format, $value);
}
}
public function collection(Collection $rows)
{
foreach ($rows as $row) {
if (empty($row['date'])) {
break;
}
Operation::firstOrCreate([
'record' => $this->transformDate($row['date'], 'd/m/Y'),
'value' => $this->transformDate($row['valeur'], 'd/m/Y'),
'description' => $row['libelle'],
'debit' => round($row['debit'] ? abs($row['debit']) : 0, 2),
'credit' => round($row['credit'] ? abs($row['credit']) : 0, 2)
]);
}
}
public function batchSize(): int
{
return 100;
}
public function chunkSize(): int
{
return 100;
}
}
<?php
namespace App\Imports;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use App\Imports\OperationSheetImport;
use Maatwebsite\Excel\Concerns\SkipsUnknownSheets;
class OperationImport implements WithMultipleSheets, SkipsUnknownSheets
{
public function sheets(): array
{
return [
1 => new OperationSheetImport(),
];
}
public function onUnknownSheet($sheetName)
{
info("Sheet ($sheetName) was skipped");
}
}
meandus liked this reply
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community