Using Laravel-5.8 and Maatwebsite-3.1, I have a table called employees (Employee).
class FirstEmployeeSheetImport implements ToModel, WithBatchInserts, WithHeadingRow, SkipsOnError, WithValidation, SkipsOnFailure
{
use Importable, SkipsErrors, SkipsFailures;
public function model(array $row)
{
$this->department = $row['department'];
$employee_data = [
'employee_code' => $row['employee_code'],
'company_id' => Auth::user()->company_id,
'email' => $row['official_email'],
'department_id' => $this->getDepartment(),
];
$employee = Employee::create($employee_data);
}
public function getDepartment(){
if(!empty($this->department) || !$this->department){
return HrDepartment::where('dept_name',$this->department)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
}
I want to use the excel upload to update these two (2) fields: email and department_id for each of the employees where:
company_id = Auth::user()->company_id AND employee_code = $row['employee_code'].
Also, it should only perform the update for those that meet the condition. I should only perform update and don't crete.
How do I achieve this?
Thanks
You can use ToCollection
to get your data into $rows
then update your data accordingly.
class FirstEmployeeSheetImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
Employee::where('company_id', auth()->user()->company_id)
->where('employee_code', $row['employee_code'])
->update([
'email' => $row['email'],
...
]);
}
}
}