PHP
Atomically Create or Update Records with `firstOrCreate` and `updateOrCreate`
Efficiently handle create-or-update operations in Laravel Eloquent using `firstOrCreate` to find or create, and `updateOrCreate` to find and update or create, avoiding race conditions.
// Example: Find a user by email, or create if not found
$user = App\Models\User::firstOrCreate(
['email' => '[email protected]'], // Attributes to find by
['name' => 'John Doe'] // Attributes to create with if not found
);
// Example: Find a product by SKU, update its price, or create if not found
$product = App\Models\Product::updateOrCreate(
['sku' => 'P12345'], // Attributes to find by
['name' => 'New Gadget', 'price' => 99.99] // Attributes to update/create with
);
How it works: The `firstOrCreate` and `updateOrCreate` methods provide a convenient way to perform 'upsert' operations (update or insert, create or update) atomically. `firstOrCreate` attempts to find a record based on the first array of attributes; if not found, it creates a new record using both the first and second arrays. `updateOrCreate` does similarly but will update an existing record found by the first array, or create a new one using both arrays if none is found. These methods help prevent race conditions and simplify logic for common data management tasks.