Bulk inserting data in Laravel is a common requirement in many applications, especially when dealing with large datasets or optimizing database operations. If you’re working with Laravel models and wondering how to handle bulk inserts, manage relationships, or ensure mass assignment protection via fillable attributes, this guide will walk you through the key aspects of achieving efficient bulk insert operations.

Table of Contents


What is Bulk Insert in Laravel?

Bulk insert refers to inserting multiple rows into a database in a single query. In Laravel, this can be achieved using the insert() method, which performs the operation efficiently at the database level. For example:

$data = [
    ['name' => 'John', 'email' => 'john@example.com', 'password' => bcrypt('password')],
    ['name' => 'Jane', 'email' => 'jane@example.com', 'password' => bcrypt('password')],
];

User::insert($data);

This method is especially helpful when dealing with large datasets, as it significantly reduces the number of database interactions, resulting in better performance.

Using Laravel Bulk Insert with Relations

In some cases, bulk insertions involve handling relationships between models. Laravel provides elegant ways to handle these scenarios.

Suppose you have a Post and Comment model. If you want to bulk insert comments related to a particular post, you can do the following:

$comments = [
    ['content' => 'Great post!', 'user_id' => 1],
    ['content' => 'Very informative.', 'user_id' => 2],
];

$post = Post::find(1);
$post->comments()->createMany($comments);

Using createMany() ensures that each inserted comment respects the fillable attributes defined in the Comment model, providing a layer of security and validation.

Laravel Bulk Insert with Query Builder

The query builder in Laravel allows for raw database operations, which can be useful for bulk inserts. For instance, you can directly insert data into a table without worrying about Eloquent models:

$data = [
    ['name' => 'John', 'email' => 'john@example.com'],
    ['name' => 'Jane', 'email' => 'jane@example.com'],
];

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

This method is faster because it bypasses Eloquent, but it also doesn’t provide mass-assignment protection like fillable attributes.

Eloquent Bulk Insert

When dealing with Eloquent bulk inserts, you might want to ensure that fillable attributes are respected. However, Eloquent’s insert() method does not trigger model events or use mass assignment rules.

To ensure fillable fields are used, you can loop through the data and call create() for each entry:

$data = [
    ['name' => 'John', 'email' => 'john@example.com', 'password' => bcrypt('password')],
    ['name' => 'Jane', 'email' => 'jane@example.com', 'password' => bcrypt('password')],
];

foreach ($data as $item) {
    User::create($item);
}

This way, Laravel’s mass-assignment protection ensures that only the attributes in the fillable property are inserted into the database.

Laravel Bulk Insert and Get IDs

A common scenario in bulk insertion is needing to retrieve the IDs of the inserted records. However, the insert() method does not return inserted IDs. To overcome this, you can either loop through the records and insert them individually or use the create() method:

$ids = [];

foreach ($data as $item) {
    $user = User::create($item);
    $ids[] = $user->id;
}

Alternatively, if performance is critical and you need the IDs, you might want to reconsider the bulk insert strategy and batch insert smaller chunks while retrieving IDs.

Bulk Insert vs. Update

Often, you need to insert or update records based on certain conditions. Laravel offers the upsert() method, available from Laravel 8 onwards, which allows you to perform this operation efficiently.

For example, you can upsert users based on their email field:

$data = [
    ['email' => 'john@example.com', 'name' => 'John', 'password' => bcrypt('password')],
    ['email' => 'jane@example.com', 'name' => 'Jane', 'password' => bcrypt('password')],
];

User::upsert($data, ['email'], ['name', 'password']);

Here, if a user with the given email already exists, their name and password will be updated. If not, a new record will be inserted.

Batch Insert in Laravel 8, 10, and 11

Starting with Laravel 8, the framework introduced several key improvements for handling bulk database operations, such as the upsert() method. This method allows you to efficiently perform insert or update operations based on unique constraints, reducing the need for additional queries or conditional logic. These features were further refined in Laravel 10, and now with Laravel 11, the framework continues to evolve with performance optimizations and more robust bulk data handling capabilities.

Batch Insert in Laravel 11

In Laravel 11, the upsert() method has been enhanced to support even more complex scenarios with improved performance. The syntax remains the same as in Laravel 8 and 10:

$data = [
    ['email' => 'john@example.com', 'name' => 'John', 'password' => bcrypt('password')],
    ['email' => 'jane@example.com', 'name' => 'Jane', 'password' => bcrypt('password')],
];

User::upsert($data, ['email'], ['name', 'password']);

Key improvements in Laravel 11 include better query optimization, making it faster and more efficient for handling large datasets. Additionally, Laravel 11 further streamlines error handling for bulk operations, ensuring smoother handling of edge cases, such as partial inserts and concurrent database operations.

For applications working with large data sets or requiring high-frequency inserts, Laravel 11 offers a more robust solution, making it the best choice if you’re planning to leverage the latest features of the framework. If you’re upgrading from an older version like Laravel 8 or 10, be sure to take advantage of these enhancements to optimize your bulk insert operations.

Conclusion

Bulk inserting data in Laravel is a powerful tool that can significantly boost your application’s performance. Whether you’re using query builder for raw inserts, Eloquent for more structured inserts, or dealing with relationships, Laravel offers several methods to handle this efficiently. Additionally, with Laravel 8 and 10, the introduction of features like upsert provides even more flexibility in handling insert or update scenarios.

Frequently Asked Questions (FAQs) on Laravel Bulk Insert Operations

1. How to do bulk insert in Laravel?

To perform a bulk insert in Laravel, you can use the insert() method, which allows you to insert multiple rows in a single database query. Here’s an example:

$data = [
    ['name' => 'John', 'email' => 'john@example.com'],
    ['name' => 'Jane', 'email' => 'jane@example.com'],
];

User::insert($data);

This method is highly efficient for inserting large datasets.

2. How to multiple insert in Laravel?

To insert multiple records in Laravel, you can either use the insert() method for raw inserts or loop through your data using the create() method, ensuring mass-assignment protection through fillable attributes:

// Using insert()
User::insert($data);

// Using create() with fillable attributes
foreach ($data as $item) {
    User::create($item);
}

The create() method respects the fillable properties of the model.

3. How to insert all data in Laravel?

To insert all data into a database table, you can use the insert() method. If you have an array of records to insert, Laravel can handle it in one query:

$data = [
    ['name' => 'John', 'email' => 'john@example.com'],
    ['name' => 'Jane', 'email' => 'jane@example.com'],
];

User::insert($data);

This approach helps reduce the number of queries and improves performance.

4. How to update multiple rows in Laravel?

To update multiple rows in Laravel, you can use the update() method along with conditions or take advantage of the upsert() method (introduced in Laravel 8) for more complex scenarios:

// Update multiple rows based on a condition
User::whereIn('id', [1, 2, 3])->update(['status' => 'active']);

// Upsert: insert or update based on a unique constraint 
$data = [ ['email' => 'john@example.com', 'name' => 'John Doe'], ['email' => 'jane@example.com', 'name' => 'Jane Doe'], ];

User::upsert($data, ['email'], ['name']);

The upsert() method will update the rows if they exist, or insert new ones if they don’t, based on the specified unique constraint (in this case, email).

5. How to insert multiple files in Laravel?

To insert multiple files in Laravel, you can handle file uploads using the request()->file() method in combination with the store() or move() method inside a loop. Here’s an example of how to handle multiple file uploads:

$files = $request->file('documents');

foreach ($files as $file) {
    $filePath = $file->store('uploads');
    // Save the file path to the database if needed
}

This allows you to upload and process multiple files efficiently in a Laravel application.

Categorized in: