Optimizing Laravel's "Update or Create" for CSV Imports
When you're importing data from a CSV file or other sources, it's essential to verify if each record is already in the database. If it is, you'd update it; if not, you'd add a new entry.
Optimizing CSV Imports in Laravel
In this CSV, you've got an array $accountsListFromCSV
, where the first column represents the account number, and the second one is the account balance:
$accountsListFromCSV = [
['610768', '630'],
['773179', '403'],
['346113', '512'],
// ... more entries ...
];
Now, let's say you've used the following code to handle this data:
foreach ($accountsListFromCSV as $entry) {
$account = Account::where('number', $entry[0])->first();
if ($account) {
$account->update(['balance' => $entry[1]]);
} else {
Account::create([
'number' => $entry[0],
'balance' => $entry[1]
]);
}
}
While this code does its job - it checks for existing accounts and updates or creates them as needed - there are some inefficiencies:
Code Length: It's a bit longer than it needs to be, given Laravel's capabilities.
Database Queries: It runs 1 or 2 queries for every single account record in the CSV.