In this episode, we're diving into the process of upserting records from a CSV file into our database. We start by setting up our ImportCsv
job so it can handle inserting (or, if necessary, updating) large chunks of data efficiently. We talk through exactly what information this job needs: the import itself, the model we're adding data to, the actual chunk of records, and the columns we want to use.
You'll see how we use constructor property promotion in PHP to keep our code clean and manageable. Then we look at upserting—meaning if a record with a matching ID already exists in the database, we skip it, otherwise we insert it as new. We even touch on how you could change the "uniqueness" identifier (like using email instead of ID) if that fits your use case better.
We'll also cover some practical details, like batching the inserts to avoid overwhelming the database, and troubleshooting when it seems like nothing's happening (hint: don't forget to restart your queue worker when you make changes!).
And finally, we verify the upsert by importing the same CSV twice to show that duplicate records aren't created. This is a great foundation for handling CSV imports cleanly and reliably. Next up, we'll focus on updating our imports table so we can track the progress of each import job.