PHP

Efficiently Create or Update Records Atomically with Eloquent `firstOrCreate`

Master the `firstOrCreate` and `updateOrCreate` methods to simplify logic for finding, creating, or updating single database records in one atomic operation.

// In a Controller or Service
use App\Models\User;
use Illuminate\Support\Str;

public function handleUserRegistrationOrUpdate(array $userData)
{
    // Example 1: firstOrCreate - Find a user by email, or create if not found.
    // The 'email' column must be unique for this to work correctly.
    $user = User::firstOrCreate(
        ['email' => $userData['email']], // Attributes to find by
        [                               // Attributes to set if creating
            'name' => $userData['name'] ?? 'Guest',
            'password' => bcrypt($userData['password'] ?? Str::random(10)),
        ]
    );

    if ($user->wasRecentlyCreated) {
        echo "User created: " . $user->name . "
";
    } else {
        echo "User found: " . $user->name . "
";
    }

    // Example 2: updateOrCreate - Find a user by email, or create/update.
    // It updates *all* attributes in the second array if the record is found.
    $userUpdated = User::updateOrCreate(
        ['email' => $userData['email']], // Attributes to find by
        [                               // Attributes to create/update
            'name' => $userData['new_name'] ?? $userData['name'],
            'password' => bcrypt($userData['new_password'] ?? $userData['password']),
            'last_login_at' => now(),
        ]
    );

    if ($userUpdated->wasRecentlyCreated) {
        echo "User created and updated: " . $userUpdated->name . "
";
    } else {
        echo "User found and updated: " . $userUpdated->name . "
";
    }

    return response()->json(['user' => $userUpdated]);
}
How it works: This snippet demonstrates Eloquent's `firstOrCreate` and `updateOrCreate` methods, which are invaluable for atomic find-or-create/update operations. `firstOrCreate` attempts to find a record by the first array of attributes; if not found, it creates a new record using both arrays. `updateOrCreate` also attempts to find a record; if found, it updates it with the attributes from the second array. If not found, it creates a new record using both. These methods help reduce boilerplate and ensure data consistency.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs