Laravel excel get total number of rows before import

Laravel excel get total number of rows before import

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Calculating Spreadsheet Row Counts for Laravel Excel Imports

When processing large datasets with maatwebsite/excel, knowing the total row count upfront is essential for building accurate progress bars or estimating import duration. However, retrieving this number isn't as straightforward as accessing a database table's ROW_COUNT(). Spreadsheets store data differently than SQL databases, and blindly iterating through them to find the count can be performance-prohibitive.

The core challenge lies in understanding how the importer interacts with the file. The standard import flow processes rows sequentially within the model method. If you simply increment a counter inside that method, as shown in your code snippet, you only know the final number after every single row has been processed. This approach renders real-time progress updates impossible because the total count remains unknown until the job finishes.

To solve this without loading the entire file into memory or iterating blindly, you must leverage the Rows object provided by the package. In modern versions of Laravel Excel (v3+), the import() method accepts a second argument: an import configuration array. Within this configuration, you can specify a callback that fires once per row, but more importantly, you can access metadata about the sheet before processing begins if you wrap your logic correctly.

However, the most robust way to get the total count is to inspect the Rows object directly after initialization or within the import event before the loop begins. The Rows object exposes a method to determine the number of rows in the sheet.

Here is how you can implement this in your controller logic:

public function postImport(Import $request)
{
    // Initialize the import instance without processing yet
    $import = new CompaniesImport;

    // Get the total number of rows from the Rows object
    // This assumes we are using the standard Excel::import signature
    // and accessing the underlying data source logic.
    
    // Note: In v3+, you often need to use the 'with' option or 
    // a custom reader to get metadata before processing.
    
    $totalRows = 0;

    // Approach A: Using the 'rows' property if accessible via reflection (not recommended)
    // Approach B: Using the import configuration to capture the count
    
    // The most reliable pattern involves using a closure that returns the total 
    // or accessing the sheet's properties.
    
    try {
        $totalRows = Excel::import($import, $request->file('file')->getPathname(), [
            'start' => 1, // Start at row 1 (default)
            'limit' => null, // Import all rows
        ]);
    } catch (\Exception $e) {
        // Handle potential errors
    }

    Session::put('importTotalRows', $totalRows);

    Excel::import($import, $request->file('file')->getPathname());

    return response()->json([
        'success' => true,
        'total_rows' => $totalRows
    ]);
}

A critical detail to note regarding your specific implementation is the handling of empty rows. Your current model method checks if (!array_filter($row)). While this prevents creating records for blank lines, it creates a logical disconnect between the "processed" count and the actual file structure. If you skip rows inside the model, the internal progress counter in the package might not align perfectly with your business logic unless you manually track valid rows separately.

For files approaching 1 million rows, memory usage is a significant concern. The Rows object holds the data for the current chunk being processed. If you attempt to force a full read of the file metadata before importing using standard PHP functions like fgetcsv, you risk hitting memory limits or timeout thresholds on shared hosting environments. Sticking to the package's internal mechanisms is safer.

Another potential pitfall involves the version of Laravel Excel you are using. In earlier versions, accessing the total count required a different strategy, often involving iterating once to count and then importing again, which doubles processing time. Modern iterations allow you to inspect the Rows object properties or utilize events like afterImport combined with session state management to track progress dynamically without a second pass.

If you require precise progress updates that account for skipped rows, consider moving the row counting logic into an event listener rather than trying to infer it from the main import loop. This decouples your validation logic from the file reading mechanism, ensuring your progress bar reflects actual successful imports rather than just file positions.

For more advanced scenarios involving massive datasets, you might want to explore chunking options or utilizing database bulk inserts instead of saving models one by one. This reduces overhead and can significantly speed up the import process, making real-time progress tracking much smoother.

Our network