Import CSV file to Laravel controller and insert data to two tables

Import CSV file to Laravel controller and insert data to two tables

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

Stefan Bogdanescu

Founder & Senior Architect

Importing CSV Data into Multiple Laravel Tables

Handling file uploads in Laravel often involves more than just moving bytes from disk to storage; you frequently need to parse that data and normalize it into your database schema. A common pattern, particularly for bulk imports, is uploading a single CSV file that defines both a grouping record (like a "List") and the individual records within that group (like "Customers").

The challenge lies in orchestrating this process: saving the list metadata first, parsing the CSV contents, and then iterating through rows to populate a second table while maintaining the relationship via foreign keys. Based on the scenarios described, here is how to architect that logic robustly.

The Two-Step Commit Strategy

The core architectural decision here is whether to handle the database writes synchronously within the controller or asynchronously via a job. For small to medium-sized datasets handled in a standard request flow, a synchronous approach inside the store method is straightforward and effective.

In your case, you have two distinct tables:

  1. lists: Stores the file reference (name) and the associated client (client_id).
  2. customers: Stores individual details (name, surname, contact_number) linked to both the specific list (list_id) and the client (client_id).

Your initial step—saving the Lists model—is correct. However, a critical detail often missed is ensuring you capture the generated ID of that new list record before attempting to import customers. If you save the list first but then fail to retrieve its ID immediately after creation, your subsequent customer records will lack the necessary list_id, breaking your relational integrity.

Parsing the CSV with PHPSpreadsheet

Laravel does not natively parse CSV files into arrays; it relies on the PHP stream wrapper. To manipulate the data row-by-row efficiently, the community standard is PHPSpreadsheet (or its lighter sibling, PhpSpreadsheet), which provides a robust Reader interface.

Here is how you can integrate that into your controller logic. You must ensure the phpoffice/spreadsheet-reader-csv package is installed if not already present:

composer require phpoffice/phpspreadsheet

Once installed, you can replace the manual parsing logic with the following implementation. This approach assumes your CSV has a header row defining the columns (name, surname, contact_number).

use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Models\List as ListModel; // Ensure correct namespace for your model
use App\Models\Customer;

public function store(Request $request)
{
    // 1. Extract input data
    $input = $request->input();
    $clientId = $request->input('client_id');

    // 2. Handle the file upload and save to storage
    if ($request->hasFile('name')) {
        $file = $request->file('name');
        
        // Generate a safe filename to avoid collisions
        $fileName = time() . '-' . $file->getClientOriginalName();
        $path = storage_path('documents');

        // 3. Create the List record FIRST
        // We need this ID immediately for the customers table
        $list = ListModel::create([
            'client_id' => $clientId,
            'name'     => $fileName,
        ]);

        // Move file to storage
        $file->move($path, $fileName);

        // 4. Read the CSV file using PHPSpreadsheet
        $spreadsheet = IOFactory::createSpreadsheetFromPath(
            storage_path('documents/' . $fileName)
        );
        
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();

        // 5. Iterate and insert customers
        // Assuming row 0 is headers, start processing from index 1
        foreach ($rows as $index => $row) {
            if ($index === 0) continue;

            // Map CSV data to model attributes
            // Adjust keys based on your actual column names in the DB
            $customerData = [
                'client_id'   => $clientId,
                'list_id'     => $list->id, // Critical: link back to the list we just created
                'name'        => $row['name'] ?? null,
                'surname'     => $row['surname'] ?? null,
                'contact_number' => $row['contact_number'] ?? null,
            ];

            Customer::create($customerData);
        }

        return view('clients'); // Or redirect with flash message
    }
}

Key Trade-offs and Pitfalls

Handling the Generated ID
The most common failure mode in this pattern is attempting to use $list before it exists or losing its ID during the file move operation. Notice in the code above, we create the ListModel, grab its $id immediately, perform the file move, and then proceed to read the CSV. This ensures that even if the file write fails (which would throw an exception), the transaction remains atomic regarding the list creation, though you might want to wrap this entire block in a try...catch or DB::transaction() for stricter data integrity.

Memory Usage with Large Files
Using $sheet->toArray() loads the entire active sheet into memory as an array. If your CSV contains tens of thousands of rows, this could spike memory usage and trigger PHP's memory_limit. For very large imports, a better approach is to use the Reader interface directly and iterate over rows individually without loading the whole sheet, similar to your second code snippet draft.

Error Handling
CSV files are notoriously inconsistent. A row might be missing a column, or contain invalid characters. Before inserting into the database, validate that $row contains all expected keys. If a row is malformed, you should log the error and skip the record rather than letting the entire import fail, or handle it via a queue job for retrying failed batches.

By separating the "list creation" logic from the "customer import" loop, you maintain clean separation of concerns and ensure that your foreign key relationships remain consistent regardless of how many customers are in the file.

Our network