Were you able to solve this?
Laravel Excel - return Collection of Models without saving them
Hi
for an app that I'm building I've createde a form (livewire component) in which the user uploads an Excel file and sets some overal parameters (this will be the parent record). When the user selects a file it is uploade by Livewire and passed on to Laravel Excel
Each row in the Excel file is parsed and converted to a model (this will be the child model).
When the user uploads the file I want to show him in a table an overview of the records that will be created.
Only when the user clicks the save button the parent model and al child models should be saved.
My Problem
When I use ToModel in laravelExcel each record is created in the database. When the Excel file is uploaded the parent record is not yet saved to the database. So no relation can be made. It is only when the user clicks save that the parent record is created and the child records should be associated.
How I tried to fix it
Currently I'm using a toCollection method to return the rows as a collection so I can show them in the form. However this feels "dirty" and not efficient.
$containerRatesCollection = Excel::toCollection(new ContainerRateExcelImport(), $this->file);
$this->containerRates = $containerRatesCollection[0];
Also because the Collection array keys are just the headers from the Excel files. The model uses different names:
$containerRate = new ContainerRate([
'fret' => $row['new_fret_usd'],
'bl_fees' => $row['bl_fees'],
'admin_fees' => $row['admin_fees'],
'container_size' => $row['cont.'],
'stuffing_fees' => $row['stuffing_fees_all_in'],
'valid_till' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['VALID TILL']),
'exchange_rate' => $row['exchange_rate'],
]);
My Question
How would you tackle this problem? I don't want to create the child records in the database without the parent record being set.
Is it possible to have Laravel Excel return a collection of unsaved models?
Please or to participate in this conversation.