Insert Multiple Records At Once With Laravel

Insert Multiple Records At Once With Laravel

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

Stefan Bogdanescu

Founder & Senior Architect

Batch Inserting Records in Laravel

The provided code snippet demonstrates a classic pattern for handling bulk data: iterating through a collection and persisting each record individually using save(). While this approach is readable and safe, it introduces significant performance bottlenecks as the dataset grows. Each call to save() triggers a separate SQL transaction, resulting in thousands of database round trips for a single API request. In high-load scenarios or when processing large CSV imports, this method becomes unsustainable due to latency and connection exhaustion.

Laravel provides more efficient mechanisms for inserting multiple records at once, primarily relying on the Query Builder's insert() method or Eloquent's bulkInsert() (available in newer versions). These methods construct a single SQL INSERT statement containing all rows, drastically reducing database overhead.

Using Query Builder for Raw Inserts

The most straightforward way to bulk insert data without creating full Eloquent models involves the Database facade and Query Builder. This approach bypasses model casting, event firing, and relationship synchronization, which are useful for individual saves but unnecessary when simply populating a table.

To replace the nested loop in your controller, you can construct an array of associative arrays representing the rows:

use Illuminate\Support\Facades\DB;

public function add(Request $request)
{
    if ($request->ajax()) {
        $books = $request->books; // Assuming this is a collection or array
        
        // Prepare data ensuring only fillable columns are included
        $data = [];
        foreach ($books as $book) {
            if (!empty($book)) {
                $data[] = [
                    'name' => $book['name'],
                    'user_id' => Auth::id(),
                    // Add other fields like timestamps if needed
                    // DB will handle default values for created_at/updated_at
                ];
            }
        }

        // Execute a single SQL INSERT statement
        DB::table('books')->insert($data);
    }
}

This implementation executes one database query regardless of the number of records. It is significantly faster than looping and is particularly effective when you do not need to trigger model events like created or handle soft deletes automatically.

Leveraging Eloquent Bulk Insert

If you prefer to stay within the Eloquent ORM ecosystem, Laravel 6 introduced bulkInsert(), which was subsequently enhanced in later versions. This method allows you to pass an array of attributes and instructs the database driver to insert them efficiently.

However, there is a critical trade-off: Eloquent model events are not fired when using bulkInsert(). This means your Book model's $booted logic, observers, or event listeners will not execute. If you rely on these for logging, auditing, or triggering side effects, the Query Builder approach with an explicit transaction is safer.

use App\Models\Book;

public function add(Request $request)
{
    if ($request->ajax()) {
        $books = $request->books;
        
        // Prepare data structure for bulk insert
        $data = [];
        foreach ($books as $bookData) {
            if (!empty($bookData)) {
                $data[] = [
                    'name' => $bookData['name'],
                    'user_id' => Auth::id(),
                ];
            }
        }

        // Perform bulk insert without triggering model events
        Book::bulkInsert($data);
    }
}

Handling Relationships and Constraints

One common pitfall when switching to batch inserts is managing foreign keys. If your books table has a user_id that references the users table, ensure that the user exists before attempting the insert. While individual saves would throw an exception upon failure, bulk inserts might behave differently depending on the database engine's error handling configuration (e.g., MySQL strict mode).

If you need to handle errors gracefully or rollback specific records, the Query Builder method wrapped in a transaction offers more granular control:

DB::transaction(function () use ($books) {
    $data = [];
    foreach ($books as $book) {
        if (!empty($book)) {
            $data[] = [
                'name' => $book['name'],
                'user_id' => Auth::id(),
            ];
        }
    }
    DB::table('books')->insert($data);
});

When to Stick With Individual Saves

Despite the performance benefits of bulk inserts, do not abandon your current loop if you require strict data validation per record or need to trigger model-specific logic. For example, if each book needs a unique slug generated based on its name and existing records, that logic is easier to manage inside a save() call where exceptions can be caught individually.

Ultimately, the choice depends on whether you prioritize speed (bulk insert) or interaction with the ORM lifecycle (individual saves). For pure data ingestion endpoints like the one in your example, optimizing the database interaction usually yields the highest return on investment.

For further reading on advanced database operations and queueing strategies for large datasets, resources such as https://laravelcompany.com often provide deep dives into scaling Laravel applications effectively.

Our network