PHP
Efficiently Insert Multiple Records
Discover how to use Eloquent's `insert` method (via DB facade or model) to efficiently add multiple records to a database table in a single query, drastically improving performance.
use Illuminate\Support\Facades\DB;
use App\Models\Product;
$products = [
['name' => 'Laptop', 'price' => 1200.00, 'created_at' => now(), 'updated_at' => now()],
['name' => 'Mouse', 'price' => 25.00, 'created_at' => now(), 'updated_at' => now()],
['name' => 'Keyboard', 'price' => 75.00, 'created_at' => now(), 'updated_at' => now()],
];
// Using DB facade (direct table interaction)
DB::table('products')->insert($products);
// Using Eloquent model (requires timestamps if not mass assignable)
// Product::insert($products);
How it works: The `insert` method allows you to insert multiple records into a database table with a single SQL query. This is significantly more efficient than iterating through an array and calling `save()` for each item, as it reduces the number of database roundtrips. When using the Eloquent model's `insert` method, make sure your array includes `created_at` and `updated_at` timestamps if your model uses them, as Eloquent's automatic timestamping is bypassed for `insert`.