PHP
Conditionally Create or Update Records with Eloquent
Master `firstOrCreate`, `firstOrNew`, and `updateOrCreate` in Laravel Eloquent to atomically find, create, or update single database records based on specific conditions.
<?php
use App\Models\User;
// Example 1: firstOrCreate - Find a user or create if not found
// It will check for a user with 'email' => '[email protected]'
// If found, return it. If not, create a new user with both 'email' and 'name'.
$user1 = User::firstOrCreate(
['email' => '[email protected]'],
['name' => 'John Doe', 'password' => bcrypt('secret')]
);
echo "User 1: " . $user1->name . "
";
// Example 2: firstOrNew - Find a user or instantiate a new model (not persisted yet)
$user2 = User::firstOrNew(
['email' => '[email protected]'],
['name' => 'Jane Doe', 'password' => bcrypt('secret')]
);
if (! $user2->exists) {
$user2->save(); // Persist the new model if it was created
echo "User 2 (new): " . $user2->name . "
";
} else {
echo "User 2 (existing): " . $user2->name . "
";
}
// Example 3: updateOrCreate - Find a user, update if found, or create if not found
// It will check for a user with 'email' => '[email protected]'
// If found, update its 'name'. If not found, create with 'email', 'name', and 'password'.
$user3 = User::updateOrCreate(
['email' => '[email protected]'],
['name' => 'Johnathon Doe', 'password' => bcrypt('newsecret')]
);
echo "User 3: " . $user3->name . "
";
How it works: `firstOrCreate()`, `firstOrNew()`, and `updateOrCreate()` are powerful methods for handling common 'find and then do something' scenarios with single records. `firstOrCreate()` attempts to find a record matching the first array of attributes; if not found, it creates a new one using both arrays. `firstOrNew()` does the same but only instantiates the model without persisting it, requiring a manual `save()`. `updateOrCreate()` finds a record by the first array, and if found, updates it with the attributes from the second array. If not found, it creates a new record using both arrays. These methods are atomic and help prevent race conditions when dealing with single records.