I'm using maatwebsite/excel to import an excel file with laravel and save data to database In my excel file I have a column name "Ref" and an other name "toRef" In my database I have a field "toRef_id" When I import a file I want to save in toRef_id, the id create where the row with Ref was equal to toRef For example
First row : Ref = First, Name = My first data, toRef = null
Second row : Ref = Second, Name = second data, toRef = null
Third row : Ref = Third, Name = My third data, toRef = First
So I want to import the first row to database with toRef_id = null. For example the id created is 1 And when I import the second row I want to save in database the toRef_id = 1
There is my controller :
function import(){
(new CustomImport)->import('myfile')
}
and CustomImport
class CustomImport implements ToModel, WithHeadingRow{
use Importable;
public function model(array $row){
Data::create([
'name' => $row['name'],
])
}
}
But I don't know how to get the id of a previous created row where $previousrow['ref'] = $row['toRef']
Could you help me please ?
class CustomImport implements ToModel, WithHeadingRow{
use Importable;
public $lastRow;
public function model(array $row){
$this->lastRow = Data::create([
'name' => $row['name'],
'previousRowId' => isset($this->lastRow->id) : $this->lastRow->id ? null
]);
}
}
Store previous created record in varibale and access it.