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, 2026•2 min read•ssbhattarai
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:
- Laravel searches for a record matching the first array (the "search criteria")
- If found, it updates that record with the second array
- If not found, it creates a new record merging both arrays
- 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