thakurcoder

January 14, 2025

· 5 min read

Understanding and Using `updateOrInsert`, `updateOrCreate`, and `upsert` in Laravel

Learn the key differences between Laravel's `updateOrInsert`, `updateOrCreate`, and `upsert`. This blog will help you understand when and why to use each method to streamline your database operations.

Laravel provides several methods to interact with your database efficiently, and updateOrInsert, updateOrCreate, and upsert are among the most useful for managing records. Knowing the differences between these methods is crucial for optimizing your database operations. Let's explore each method, their usage, and when to apply them in your projects.

What is updateOrInsert?

updateOrInsert is a Query Builder method that allows you to either update an existing record or insert a new one if no matching record is found. It's a great tool when you need a simple, no-frills solution to manage records based on certain conditions.

Key Features:

  • Use Case: Ideal for simple single-record operations.
  • Return Type: Boolean (true if the record was inserted or updated).
  • Model Dependency: Does not require an Eloquent model.
  • Performance: Not the most efficient for bulk operations.

Example:

DB::table('users')->updateOrInsert(
    ['email' => 'user1@example.com'],  // Search by email
    ['name' => 'User One', 'age' => 25] // Update or insert with name and age
);

SQL Generated:

  • Update:
    UPDATE `users` SET `name` = 'User One', `age` = 25 WHERE `email` = 'user1@example.com';
  • Insert:
    INSERT INTO `users` (`email`, `name`, `age`) VALUES ('user1@example.com', 'User One', 25);

What is updateOrCreate?

updateOrCreate is an Eloquent method that tries to find a record based on the provided attributes. If it finds the record, it will update it; otherwise, it will create a new one. This method is perfect for working with Eloquent models when you need to use model features like casting and relationships.

Key Features:

  • Use Case: Best for single-record operations with Eloquent features.
  • Return Type: Model instance.
  • Model Dependency: Requires an Eloquent model.
  • Triggers Eloquent Events: Yes, it triggers events like saving, saved, etc.

Example:

use App\Models\User;
 
User::updateOrCreate(
    ['email' => 'user1@example.com'],  // Search by email
    ['name' => 'User One', 'age' => 25] // Update or create with name and age
);

SQL Generated:

  • Update:
    UPDATE `users` SET `name` = 'User One', `age` = 25 WHERE `email` = 'user1@example.com';
  • Insert:
    INSERT INTO `users` (`email`, `name`, `age`) VALUES ('user1@example.com', 'User One', 25);

[[NEWSLETTER]]

 
---
 
## What is `upsert`?
 
**`upsert`** is a Query Builder method designed for bulk insert or update operations. This method allows you to efficiently insert or update multiple records in a single query, making it ideal for handling large datasets.
 
### **Key Features**:
- **Use Case**: Best for bulk insert or update operations.
- **Return Type**: Number of affected rows.
- **Model Dependency**: Does not require an Eloquent model.
- **Performance**: Highly efficient for bulk operations, minimizing the number of database queries.
 
### **Index Requirement for `upsert`**:
One important thing to note when using the `upsert` method is that **indexes** on the columns being used for matching (i.e., the unique identifier columns) are critical for the performance of the operation. Laravel will attempt to find existing records based on the unique identifiers you specify, and having an index on these columns ensures that the operation is performed efficiently, especially when dealing with large datasets.
 
### **Example**:
```php
DB::table('users')->upsert(
  [
      ['email' => 'user1@example.com', 'name' => 'User One', 'age' => 25],
      ['email' => 'user2@example.com', 'name' => 'User Two', 'age' => 30],
  ],
  ['email'], // Unique identifier
  ['name', 'age'] // Columns to update if record exists
);

SQL Generated:

INSERT INTO `users` (`email`, `name`, `age`)
VALUES 
  ('user1@example.com', 'User One', 25),
  ('user2@example.com', 'User Two', 30)
ON DUPLICATE KEY UPDATE 
  `name` = VALUES(`name`), 
  `age` = VALUES(`age`);

Comparison of updateOrInsert, updateOrCreate, and upsert

1. updateOrInsert:

  • Type: Query Builder method.
  • Use Case: Ideal for single-record operations without needing Eloquent features.
  • Return Value: Boolean (true if inserted or updated).
  • Bulk Operations: Not suited for bulk operations.
  • Performance: Not optimal for bulk; better for individual record operations.
  • Triggers Eloquent Events: No.

2. updateOrCreate:

  • Type: Eloquent method.
  • Use Case: Best when using Eloquent models and requiring model features such as casting and relationships.
  • Return Value: Model instance.
  • Bulk Operations: Not suited for bulk operations.
  • Performance: Suitable for single-record operations with Eloquent.
  • Triggers Eloquent Events: Yes, events like saving, saved, etc.

3. upsert:

  • Type: Query Builder method.
  • Use Case: Ideal for bulk insert or update operations.
  • Return Value: Number of affected rows.
  • Bulk Operations: Optimized for bulk operations.
  • Performance: Most efficient for bulk insert or update.
  • Triggers Eloquent Events: No.
  • Index Requirement: Requires indexes on the unique identifier columns for better performance during matching.

Conclusion

Understanding the differences between updateOrInsert, updateOrCreate, and upsert is vital for choosing the right method based on your specific requirements.

updateOrInsert is perfect for quick, individual record updates or inserts using the query builder.

updateOrCreate is best when working with Eloquent models and needing the extra features such as events and relationships.

upsert is the most efficient choice when handling bulk operations, updating or inserting multiple records at once.

By selecting the appropriate method, you can streamline your code and ensure better performance in your Laravel applications.