PHP
Perform Atomic Insert or Update Operations with Eloquent `updateOrCreate`
Simplify your database logic by using Laravel Eloquent's `updateOrCreate` method to efficiently insert a new record or update an existing one atomically.
use App\Models\User;
// Scenario: We want to find a user by email, if they exist, update their name.
// If not, create a new user with the given email and name.
$user = User::updateOrCreate(
['email' => '[email protected]'],
['name' => 'John Doe', 'password' => bcrypt('secret')]
);
// Scenario: Update a product's price, or create it if it doesn't exist by SKU
use App\Models\Product;
$product = Product::updateOrCreate(
['sku' => 'P-001-RED'],
['name' => 'Red Widget', 'price' => 19.99, 'description' => 'A vibrant red widget.']
);
// The $user and $product variables now hold the created or updated model instance.
How it works: The `updateOrCreate` method attempts to locate a model using the first array of attributes. If a model is found, it will be updated with the attributes provided in the second array. If no model is found, a new one will be created with both sets of attributes. This method is incredibly useful for 'upsert' operations, ensuring atomicity and reducing boilerplate code for common create-or-update scenarios.