PHP
Perform Efficient Bulk Inserts and Updates with Eloquent
Learn to use `insert()` for efficient bulk record creation and `update()` or `upsert()` for mass updates and 'insert or update' operations in Laravel Eloquent.
// Bulk Insert using the Query Builder (most efficient for many records, skips model events)
DB::table('users')->insert([
['name' => 'John Doe', 'email' => '[email protected]', 'password' => 'secret', 'created_at' => now(), 'updated_at' => now()],
['name' => 'Jane Smith', 'email' => '[email protected]', 'password' => 'secret', 'created_at' => now(), 'updated_at' => now()],
]);
// Bulk Update using a where condition
App\Models\Product::where('category_id', 5)->update(['status' => 'inactive', 'updated_at' => now()]);
// Upsert (insert or update multiple records in one query, Laravel 8+)
App\Models\Book::upsert(
[
['id' => 1, 'title' => 'Book One Updated', 'price' => 25, 'author_id' => 1],
['id' => 2, 'title' => 'Book Two', 'price' => 30, 'author_id' => 1],
['id' => 3, 'title' => 'New Book', 'price' => 45, 'author_id' => 2],
],
['id'], // Columns that uniquely identify records
['title', 'price'] // Columns to update if a match is found
);
How it works: When dealing with a large number of database records, performing individual `save()` operations can be resource-intensive. Laravel provides more efficient methods for bulk operations. `DB::table()->insert()` allows for inserting multiple records in a single query, bypassing Eloquent model events for maximum performance. For mass updates, `update()` on a query builder applies changes to all matching records. `upsert()`, available since Laravel 8, is a powerful method that can insert records if they don't exist or update them if they do, handling multiple rows in a single, optimized database query.