I'm using Laravel 8 with the Excel package. I have an array from a csv import as:
array("Mr", "Tom", "Staff", "and", "Mr", "John", "Doe")
In my model function below, I am struggling to add 2 separate records for these two without duplicating code. In the code above, all I do is sort the csv data into their correct fields as title, firstName etc. It's all sorted into an array called name which is inside the object homeowner So:
title = Mr
firstName = Tom
lastName = Staff
title2 = Mr
firstName2 = John
lastName2 = Doe
public function model(array $row) { if (count($row) == 3) { $homeowner = new ThreeWordName($row); }elseif (count($row) == 7) { $homeowner = new SevenWordName($row); } $sorter = new CsvNameSorter; $sorter->sort($homeowner); return new temp_csv_data([ 'title' => $homeowner->name['title'], 'firstName' => $homeowner->name['firstName'], 'lastName' => $homeowner->name['lastName'], 'title' => $homeowner->name['title2'], 'firstName' => $homeowner->name['firstName2'], 'lastName' => $homeowner->name['lastName2'], ]); }
CodePudding user response:
As importing to model in Laravel Excel
, is about mapping one row to a model, if you use importing to model.
Instead you could import to a collection and create your logic.
public function collection(Collection $rows)
{
foreach($rows as $row) {
if (count($row) == 3) {
$homeowner = new ThreeWordName($row);
}elseif (count($row) == 7) {
$homeowner = new SevenWordName($row);
}
$sorter = new CsvNameSorter;
$sorter->sort($homeowner);
TempCsvData::create([
'title' => $homeowner->name['title'],
'firstName' => $homeowner->name['firstName'],
'lastName' => $homeowner->name['lastName'],
]);
TempCsvData::create([
'title' => $homeowner->name['title2'],
'firstName' => $homeowner->name['firstName2'],
'lastName' => $homeowner->name['lastName2'],
]);
}
}
As a note, class naming is pascal cased.