PHP
Bulk Insert Multiple Records Efficiently with Eloquent `insert`
Optimize database performance by using Eloquent's `insert` method for bulk insertion of multiple records, bypassing model events for speed.
<?php
use App\Models\Product;
use Illuminate\Support\Facades\DB;
// Example data array for bulk insertion
$products = [
[
'name' => 'Laptop Pro',
'sku' => 'LAP-P-001',
'price' => 1200.00,
'created_at' => now(),
'updated_at' => now(),
],
[
'name' => 'Mechanical Keyboard',
'sku' => 'KB-MECH-002',
'price' => 150.00,
'created_at' => now(),
'updated_at' => now(),
],
[
'name' => 'Wireless Mouse',
'sku' => 'MOUSE-WL-003',
'price' => 75.00,
'created_at' => now(),
'updated_at' => now(),
],
];
// Using the DB facade for direct bulk insert
// DB::table('products')->insert($products);
// Using the Eloquent model's insert method (requires fillable/guarded setup if using create/save individually, but not for raw insert)
Product::insert($products);
// Important: Model events (e.g., 'creating', 'created') and mass assignment protection will NOT be fired
// when using insert directly. Timestamps must be manually provided if desired.
How it works: The 'insert' method (available on the 'DB' facade and Eloquent models) provides a highly efficient way to insert multiple records into the database with a single query. Unlike iterating and calling 'create()' or 'save()' for each record, 'insert' bypasses model events, mass assignment protection, and automatic timestamping, making it significantly faster for bulk operations where these features are not required.