PHP
Atomically Create or Update Records
Learn how to use Eloquent's firstOrCreate and updateOrCreate methods to efficiently create a new record or retrieve/update an existing one in Laravel applications, ensuring atomicity.
use App\Models\User;
// Find user by email, or create if not found.
// If found, it will use the existing record.
$user = User::firstOrCreate(
['email' => '[email protected]'],
['name' => 'John Doe'] // These attributes are set if creating
);
// Find user by email, or create a new one.
// If found, update its 'name' attribute. If not found, create with both.
$user = User::updateOrCreate(
['email' => '[email protected]'],
['name' => 'Jane Doe Updated', 'password' => bcrypt('new_password')]
);
How it works: The `firstOrCreate` method attempts to find a record using the first array of attributes. If a match is found, the existing model instance is returned. If no match is found, a new model instance is created with both the first and second array of attributes. The `updateOrCreate` method works similarly but updates the model attributes if a match is found. Both methods are atomic, meaning they safely handle race conditions where multiple requests might try to create the same record simultaneously, preventing duplicates.