Laravel Pro Tips

Laravel Pro Tips

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.

Laravel Pro Tips's avatar
Laravel Pro Tips
Oct 26, 2023
∙ Paid
Share

man in blue denim jacket facing turned on monitor
Photo by Austin Distel on Unsplash

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:

  1. Code Length: It's a bit longer than it needs to be, given Laravel's capabilities.

  2. Database Queries: It runs 1 or 2 queries for every single account record in the CSV.

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 Laravel Pro Tips
Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for great culture