PHP
Perform Atomic Insert or Update (Upsert) Operations
Discover Eloquent's `upsert()` method to atomically insert new records or update existing ones based on unique constraints, simplifying complex database logic.
use App\Models\User;
User::upsert(
[
['email' => '[email protected]', 'name' => 'John Doe'],
['email' => '[email protected]', 'name' => 'Jane Smith'],
],
['email'], // Columns used to identify unique records
['name'] // Columns to update if a matching record exists
);
// Example with an existing user (assuming '[email protected]' exists)
User::upsert(
[['email' => '[email protected]', 'name' => 'Johnathon Doe']],
['email'],
['name']
);
How it works: The `upsert()` method allows you to insert records that do not exist or update records that do exist based on a given unique constraint. The first argument is an array of data arrays to upsert. The second argument specifies the columns that should be considered unique (e.g., `email`). The third argument lists the columns that should be updated if a matching record is found. This provides an atomic way to synchronize data, preventing race conditions and simplifying your application logic.