PHP
Atomic Record Creation or Update with Eloquent
Learn Laravel Eloquent's powerful `firstOrCreate`, `firstOrNew`, and `updateOrCreate` methods for atomically handling record existence and creation/update logic.
use App\Models\User;
// --- firstOrCreate: Find a user by credentials, or create if not found ---
// Attempts to find a user where 'email' is '[email protected]'.
// If not found, a new user is created with 'email' as '[email protected]'
// AND 'name' as 'Test User'.
// The second array contains attributes to be used if the model is created.
$user = User::firstOrCreate(
['email' => '[email protected]'],
['name' => 'Test User']
);
echo "firstOrCreate User ID: " . $user->id . "
";
// --- firstOrNew: Find a user by credentials, or return a new instance ---
// Attempts to find a user where 'email' is '[email protected]'.
// If not found, a new User *instance* is returned, but NOT saved to the database.
// The second array fills attributes on the new instance.
$newUser = User::firstOrNew(
['email' => '[email protected]'],
['name' => 'New User Placeholder']
);
if (!$newUser->exists) {
$newUser->save(); // Manually save if it's a new instance
echo "firstOrNew User created with ID: " . $newUser->id . "
";
} else {
echo "firstOrNew User found with ID: " . $newUser->id . "
";
}
// --- updateOrCreate: Find a user by credentials, or create/update it ---
// Attempts to find a user where 'email' is '[email protected]'.
// If found, the 'name' and 'password' attributes are updated.
// If not found, a new user is created with all attributes specified.
$updatedUser = User::updateOrCreate(
['email' => '[email protected]'],
['name' => 'Updated Name', 'password' => bcrypt('secret')]
);
echo "updateOrCreate User ID: " . $updatedUser->id . "
";
How it works: These methods provide atomic ways to handle record creation or updates based on existing data. `firstOrCreate` finds a record by the first array's attributes, or creates it using both arrays. `firstOrNew` finds a record or returns a new unsaved instance. `updateOrCreate` finds a record by the first array's attributes and updates it with the second array's data, or creates a new record using both arrays if not found.