In this episode, we dive into how to import CSV files into our Laravel application, which is super similar to exporting – you’ll notice the syntax barely changes! We start by making sure our model is set up for importing, just like with exporting. We generate a new import class using Artisan and drop it in the imports folder. For consistency (and reusability), we also create an importable interface or trait – totally optional, but keeps things neat if you’re into interfaces.
We set up the actual queueing process for the import, using the real path to the uploaded CSV file and specifying details like the disk and file type. To handle large files efficiently, we chunk the import to process 1000 rows at a time, and implement the ShouldQueue
interface so the whole import runs in the background.
Next, we debug what a row from our CSV actually looks like by logging it out, and discover how to handle the heading row (the column names) with Laravel Excel's interface. With that sorted, we map each piece of incoming data to our transaction fields – transaction ID, descriptor, amount, and date. We do a quick check by clearing out the DB, running an import, and confirming that everything appears as expected (including transforming currencies and dates nicely through Laravel’s casting feature).
One last important feature: upserts! If you import a new row with a transaction ID that already exists, you’ll want it to update instead of throwing an error or duplicating data. We enable upserts in our import class, with a quick reminder that you’ll need a unique index or primary key on the relevant column (transaction_id in our case). After changing a row’s value in the CSV and re-importing, you’ll see the database gets updated rather than adding a duplicate row!
So, by the end of this episode, you’ve got a streamlined, reliable way to import (and update) records from CSVs right into your app, ready for whatever your application needs.