Laravel return error on duplicate column in CSV using maatwebsite/excel

Viewed 52

I have code which i am using to import a CSV using the maatwebsite/excel package in Laravel.

I am importing to a collection, but before that i am using the rules method to run some validation.

I have the following validation rule to check the DB for user id's that already exist.

'user_id' => ['required', 'unique:user,id', 'string', 'max:60'],

But I also want to check that the same user id does not appear multiple times in the same column of the actual CSV file.

Is this possible?

2 Answers

Use it like this:

'user_id' => ['required', 'unique:your_csv_table_name,user_id', 'string', 'max:60'],

I use updateOrCreate function to avoid duplicate records https://laravel.com/docs/9.x/eloquent#upserts

$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);
Related