PHP
Performing Efficient Batch Inserts with DB Facade's insert()
Improve database write performance in Laravel by using the `DB::table()->insert()` method for efficient batch creation of multiple records without triggering model events.
use Illuminate\Support\Facades\DB;
$usersToInsert = [
['name' => 'Alice', 'email' => '[email protected]', 'password' => bcrypt('secret'), 'created_at' => now(), 'updated_at' => now()],
['name' => 'Bob', 'email' => '[email protected]', 'password' => bcrypt('secret'), 'created_at' => now(), 'updated_at' => now()],
['name' => 'Charlie', 'email' => '[email protected]', 'password' => bcrypt('secret'), 'created_at' => now(), 'updated_at' => now()],
];
DB::table('users')->insert($usersToInsert);
echo "Successfully inserted " . count($usersToInsert) . " users in a single query.";
How it works: When you need to insert a large number of records, using `DB::table('table_name')->insert()` is significantly more efficient than looping through an array and calling `Model::create()` for each record. This method performs a single database query for all records, reducing overhead. It bypasses Eloquent models, meaning model events (like `creating`, `created`) and mass assignment protection are not applied, making it ideal for performance-critical batch operations.