PHP
Efficiently Batch Insert Multiple Records
Learn how to use Eloquent's `insert()` method for efficient batch insertion of multiple records into your database, significantly reducing query overhead.
use App\Models\Product;
use Illuminate\Support\Carbon;
$productsToInsert = [
[
'name' => 'Laptop',
'price' => 1200.00,
'description' => 'Powerful portable computer',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Mouse',
'price' => 25.00,
'description' => 'Wireless ergonomic mouse',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
// ... more products
];
Product::insert($productsToInsert);
How it works: This snippet demonstrates how to use `Product::insert($data)` for efficient batch insertion. Instead of calling `create()` for each record, which would execute multiple SQL `INSERT` statements, `insert()` generates a single SQL query for all provided records. This significantly improves performance when adding many records at once by reducing database round trips. Note that this method does not hydrate model instances or fire model events.