0

I'm using Maatwebsite\Excel to import a csv file to store new users in the DB. If i have already a record in DB with the same data it creates and error. How can i update the record if it exists ?

My import class is :

class UsersImport implements ToModel, WithCustomCsvSettings, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'firstname' => $row['firstname'],
            'lastname' => $row['lastname'],
            'email' => $row['email'],
            'password' => $row['pass'],
            'created_at' => $row['registered'],
        ]);
    }

    public function getCsvSettings(): array
    {
        return [
            'delimiter' => ","
        ];
    }
}

1 Answer 1

1

You should implement the WithUpserts interface. Also you need to specify which field should be unique so if it exists, it will update the record, else it will create new one.

Assuming your unique column is email, change your code to the following:

class UsersImport implements ToModel, WithCustomCsvSettings, WithHeadingRow, WithUpserts
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        return new User([
            'firstname' => $row['firstname'],
            'lastname' => $row['lastname'],
            'email' => $row['email'],
            'password' => $row['pass'],
            'created_at' => $row['registered'],
        ]);
    }

    public function getCsvSettings(): array
    {
        return [
            'delimiter' => ","
        ];
    }

    public function uniqueBy()
    {
        return 'email';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.