Laravel excel get total number of rows before import
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
When working on large spreadsheets with hundreds of thousands or even millions of rows, it's essential to know the total count before starting the import process. This allows you to create a progress bar and monitor the import status without affecting performance. In this blog post, we will discuss how to get the total number of rows in a Laravel Excel spreadsheet and utilize that information for efficient data imports.
The Issue: Without knowing the total row count, you could potentially exceed your database's maximum capacity or run into other performance issues during the import process. For better control and insights, we need to retrieve this crucial piece of information as early as possible in our code.
The Solution: Thankfully, Laravel Excel provides an easy way to get this data using the static all() method. This will return an array containing all rows from your spreadsheet without actually importing them into memory or storing them on disk.
$rowCount = \Illuminate\Support\Collection::all(fn () => \Maatwebsite\Excel\Facades\Excel::rows($file))->count();
Analyzing the Code: In the above example, we use the Collection class to perform a count operation on an array containing all rows from our spreadsheet. The Collection is populated by calling the rows() method inside the callable function and passing the necessary file path or stream as input.
Potential Optimizations: While this approach provides a reliable solution, it may introduce additional overhead due to loading all rows from the spreadsheet. If performance is of utmost importance, consider using a simple counter during importing process instead. This can be done by incrementing a static variable each time a new row is processed.
Importing and Monitoring Progress: With the total number of rows in hand, you can now create your progress bar and update it as data is imported using techniques like database transactions or sessions. This way, you have real-time information on where the import stands and can easily prevent any errors caused by outdated data.
Conclusion: Knowing the total count of rows in a spreadsheet before importing is crucial for efficient handling of large datasets. By utilizing Laravel Excel's all() method or creating your own custom counter, you can ensure smooth and well-informed imports that won't slow down your application or overwhelm your database.
Laravel Company Resources: