Master Laravel's updateOrCreate() for Smarter Database Operations

Stop writing repetitive if-else logic to check if records exist before updating or creating them. Laravel's updateOrCreate() method handles both operations intelligently in a single, elegant call.

January 31, 20262 min readssbhattarai

The Problem

How many times have you written code like this?

$user = User::where('email', $request->email)->first();

if ($user) {
    $user->update([
        'name' => $request->name,
        'phone' => $request->phone,
    ]);
} else {
    $user = User::create([
        'email' => $request->email,
        'name' => $request->name,
        'phone' => $request->phone,
    ]);
}

It works, but it's verbose and requires extra queries.

The Solution: updateOrCreate()

Laravel provides a cleaner way to handle this pattern:

$user = User::updateOrCreate(
    ['email' => $request->email],  // Search by this
    [
        'name' => $request->name,   // Update or create with this
        'phone' => $request->phone,
    ]
);

How it works:

  1. Laravel searches for a record matching the first array (the "search criteria")
  2. If found, it updates that record with the second array
  3. If not found, it creates a new record merging both arrays
  4. Returns the model instance either way

Pro Tips

1. Use with fillable/guarded. Make sure your model allows mass assignment for the fields you're updating:

class User extends Model
{
    protected $fillable = ['email', 'name', 'phone'];
}

 

When to Use It

Perfect for:

  • API data synchronization
  • Import/export operations
  • User settings and preferences
  • Idempotent API endpoints
  • Upserting records from external sources

Not ideal for:

  • When you need different logic for create vs. update
  • When validation rules differ between operations
  • Complex conditional updates