In this episode, we focus on improving the way we read CSV files in our Livewire component. Previously, we were directly calling a method to read the CSV, but now we're refactoring this to use a computed property. This not only gives us some free caching benefits, but also makes it clearer and easier to reuse reading logic later—helpful since we'll need to access the CSV data multiple times (for example, when we kick off batching and queue processing).
First, we set up a getReadCsvProperty
so whenever we need the CSV reader, we reference this property instead of the direct method. This keeps our code a bit cleaner and lays the groundwork for further improvements.
Next, we add another computed property for getting the actual CSV records. Using the League CSV library we're already using, we pipe our reader through a Statement
to get an iterable set of records. It’s worth noting that this gives us a PHP generator, so there are some nuances here we'll cover in more detail later—especially when it comes to batching the records for processing in chunks.
Finally, we connect everything up so that we can quickly count the total rows in the imported CSV. We test it out by importing a file and confirming the row count shows as expected. With this foundation set, we're now ready to move onto chunking these records and putting them into a queue for background processing in the next steps!