PHP

Bulk Insert Multiple Records Efficiently with Eloquent

Perform high-performance bulk insertions of multiple records into your database using Laravel Eloquent's `insert()` method, significantly faster than looping `create()` calls.

<?php

use App\Models\Product;
use Illuminate\Support\Facades\DB;

$productsData = [
    [
        'name' => 'Laptop', 
        'price' => 1200.00, 
        'stock' => 50, 
        'created_at' => now(), 
        'updated_at' => now()
    ],
    [
        'name' => 'Mouse', 
        'price' => 25.00, 
        'stock' => 200, 
        'created_at' => now(), 
        'updated_at' => now()
    ],
    [
        'name' => 'Keyboard', 
        'price' => 75.00, 
        'stock' => 100, 
        'created_at' => now(), 
        'updated_at' => now()
    ],
];

// Option 1: Using the Eloquent Model directly
Product::insert($productsData);

// Option 2: Using the DB facade (more direct, bypasses Eloquent events)
// DB::table('products')->insert($productsData);

echo "Successfully inserted multiple products.";
How it works: When you need to insert many records into the database, using Eloquent's `insert()` method (or `DB::table()->insert()`) is far more efficient than calling `Model::create()` in a loop. The `insert()` method performs a single SQL query to insert all records at once, drastically reducing database round trips and improving performance. Note that `insert()` bypasses Eloquent model events and automatic timestamp updates unless you manually include `created_at` and `updated_at` in your data array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs