In this episode, we dive into handling CSV file uploads using Livewire. We start off by setting up file upload functionality, creating a property in our Livewire component to hold the temporary file (called file
), and attaching our input field to this property with wire:model
. We also cover basic validation to make sure only CSVs are accepted and put a 10MB file size limit in place.
Once uploading is wired up, we test the flow and use dump()
to confirm that our file is in fact being uploaded and stored temporarily. Next, we update our state management so that different UI elements (like the "Import" button or record counts) appear only when a file is present.
The bulk of this video focuses on efficiently counting the rows in a CSV file without loading the entire thing into memory, using PHP's built-in SPLFileObject
. We cover a neat trick with seeking to the largest possible integer to get the total row count, and we consider scenarios where the CSV might have headers, adjusting the count as needed.
By the end, you’ll see the UI dynamically update with the number of records about to be imported after uploading a CSV, and the process is fast enough for really big files. Next up, we'll actually start working on importing those records!