Bulk Insert/Update in Laravel Query Builder: Tutorial & Examples

Updated: January 16, 2024 By: Guest Contributor Post a comment

Overview

Working with database operations is an integral part of developing applications in Laravel. In scenarios where you have to insert or update large datasets in a database, utilizing bulk operations can be a crucial performance enhancement. Laravel’s Query Builder provides a fluent interface to handle such operations efficiently. In this tutorial, we’ll learn how to perform bulk insert and update operations using Laravel Query Builder and explore a range of examples that escalate from basic to advanced.

Introduction to Bulk Operations

Bulk operations refer to the process of inserting or updating multiple rows in a database table in a single query. This is more efficient than running an individual insert or update statement for each row, as it reduces the overhead of multiple database round trips. In Laravel, bulk operations are facilitated through its eloquent Query Builder, offering a simple and expressive syntax.

Preparing the Environment

Before we dive into the examples, ensure you have a working Laravel environment and a database connection defined in your .env file. Additionally, you’ll need to have a table set up in your database for the insert and update operations. For this tutorial, let’s work with a hypothetical ‘users’ table.

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamps();
});

Basic Bulk Insert

The most straightforward bulk operation is the insert. Laravel’s Query Builder allows inserting multiple records at once using the insert() method.


$users = [
 ['name' => 'John Doe', 'email' => '[email protected]'],
 ['name' => 'Jane Doe', 'email' => '[email protected]']
];

DB::table('users')->insert($users);

After this operation, both John and Jane would be added to the ‘users’ table. This method is a basic example of how to perform a bulk insert.

Bulk Update Basics

Bulk updates are trickier because each row may need different data. Laravel doesn’t have a built-in method for bulk updates analogous to insert. Instead, you’ll often need to iterate over each item. Here’s a basic example:


$users = [
 ['id' => 1, 'name' => 'John Updated'],
 ['id' => 2, 'name' => 'Jane Updated']
];

foreach ($users as $user) {
 DB::table('users')
 ->where('id', $user['id'])
 ->update(['name' => $user['name']]);
}

This example demonstrates how one might iterate over an array of users to update their names based on their IDs. While this approach technically works, it isn’t the most efficient way to handle bulk updates in a real-world application, especially with a large dataset.

Advanced Bulk Insert with Eloquent

Laravel’s Eloquent ORM presents another way to perform bulk inserts using the insert() method. With Eloquent, the syntax is very similar but utilizes Model instances. Assume that you have a corresponding User model:

 
$users = [
 ['name' => 'Michael Scott', 'email' => '[email protected]'],
 ['name' => 'Dwight Schrute', 'email' => '[email protected]']
];

User::insert($users);

This example illustrates how the same bulk insert can be done using Eloquent’s ORM syntax.

Chunk Wise Updates

For updating large datasets, Laravel provides a method chunk() which can be used to update a set of records while minimizing memory usage. Below is how you can leverage the method to perform batch updates efficiently.


$updatedUsers = [
 'John Updated', 'Jane Updated'
];

DB::table('users')->orderBy('id')->chunk(100, function ($users) use ($updatedUsers) {
 foreach ($users as $index => $user) {
 DB::table('users')
 ->where('id', $user->id)
 ->update(['name' => $updatedUsers[$index]]);
 }
});

This executes the update in chunks of 100 records, helping to keep memory usage low when working with large datasets.

Efficient Bulk Update with Case Statements

An advanced method for performing a bulk update in Laravel uses MySQL’s CASE syntax to update multiple rows differently in a single query. The Query Builder can be used to construct such a query like so:


$values = [
 ['id' => 1, 'name' => 'Jim Halpert'],
 ['id' => 2, 'name' => 'Pam Beesly']
];

$case = "CASE id " ;
foreach ($values as $value) {
 $case .= "WHEN {$value['id']} THEN '{$value['name']}' ";
}
$case .= "END";

$ids = implode(',', array_column($values, 'id'));

DB::update("UPDATE users SET name = $case WHERE id IN ($ids)");

This is a more advanced usage of the Query Builder, crafting a custom query that takes full advantage of SQL to implement a bulk update efficiently in one database round trip.

Conclusion

In this guide, we’ve explored how to execute bulk insert and update operations in Laravel, ranging from simple to more complex scenarios. Knowing how to leverage these techniques can dramatically improve the performance of your application, especially when dealing with large datasets. Always remember to use these operations responsibly and consider the caveats, like data integrity and potential performance bottlenecks, within your specific application context.