devionti
1 month ago
248
5
Laravel

Laravel Excel Import Update Existing

Posted 1 month ago by devionti

I read through the documentation and I am unsure on how to update existing instead of creating new entries

class ImportUsers extends Command
{
    protected $signature = 'import:users';

    protected $description = 'Laravel Excel importer';

    public function handle()
    {
        $this->output->title('Starting import Users');
         (new UsersImport)->withOutput($this->output)->import('Imports/users.xlsx'); 
    }
}
class UsersImport implements ToModel, WithBatchInserts, WithChunkReading, WithHeadingRow, WithProgressBar
{
    use Importable;

    public function model(array $row)
    {
        return new User ([
            'id' => $this->transformNameToId($row['Name']),
            'name' => $row['Name of Employee'],
            'nationality' => $row['Nationality'],
            'position' => $row['Position'],
	]);
}
}

    public function transformNameToId($value) {
        $user = User::where('name', $value)->first();
    
        if(! $user){
            return null;
        }
    
        return $user->id;
    }

https://docs.laravel-excel.com/3.1/imports/

Please sign in or create an account to participate in this conversation.