Navigation

Laravel

How to Use `updateOrCreate()` in Laravel

Learn how to use Laravel's updateOrCreate() method to insert or update records in a single query. Perfect for syncing data and avoiding duplicate entries.

Problem: You need to either update an existing record or create a new one if it doesn't exist, but writing separate logic for checking existence is tedious.

Solution:

// Update user if email exists, otherwise create new user
$user = User::updateOrCreate(
    ['email' => 'john@example.com'],  // Search attributes
    [                                  // Values to update/create
        'name' => 'John Doe',
        'status' => 'active',
        'last_login' => now()
    ]
);

// Example with multiple search conditions
$order = Order::updateOrCreate(
    [
        'user_id' => $userId,
        'product_id' => $productId,
        'status' => 'pending'
    ],
    [
        'quantity' => $request->quantity,
        'price' => $product->price
    ]
);

Why it works: The first array contains the attributes Laravel uses to find the record. If a match is found, it updates with the second array's values. If no match exists, it creates a new record combining both arrays. This eliminates the need for separate exists() checks and conditional create/update logic.

Note: Behind the scenes, this uses firstOrNew() followed by fill() and save(), wrapped in a database transaction for safety.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel