Laravel Update if record exists or Create if not

Laravel Update if record exists or Create if not

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

You're currently solving the "update if exists, create if not" problem by fetching the record into memory and then conditionally saving it. This logic is sound: you query for a MerchantBranchToken, check if it's null, instantiate a new model if missing, or update the existing one if found. While this works perfectly, it feels a bit verbose compared to what Laravel can do out of the box. The core issue in your snippet isn't the logic itself, but rather the manual handling of the relationship and the explicit if/else block.

The most idiomatic way to handle this in Laravel is using the updateOrCreate method on the parent model. This single line replaces your entire conditional block:

$token = MerchantBranch::find($id)->token()->updateOrCreate(
    ['merchant_branch_id' => $id], // The foreign key constraint
    ['token' => $token]           // The column to update/create
);

However, as you noted in your source material, you ran into a snag regarding the fillable property. This is a crucial detail often overlooked when adopting this pattern. The updateOrCreate method performs an SQL UPDATE statement under the hood. If the model's $fillable array does not include every column present in the second argument of updateOrCreate, Laravel will silently ignore those attributes or, depending on your configuration and database settings, throw an exception.

To make this work without modifying every single token update, you have two primary options:

1. Whitelist the Attributes

Ensure that merchant_branch_id is explicitly listed in your MerchantBranchToken model's $fillable array. Even though you are logically passing the parent ID to establish the relationship, the database needs permission to write to that column if it isn't strictly defined as part of a foreign key constraint or a hidden attribute.

class MerchantBranchToken extends Model
{
    protected $fillable = [
        'token',
        'merchant_branch_id', // Must be here for updateOrCreate to work
        // ... other writable fields
    ];

    public function merchant_branch()
    {
        return $this->belongsTo('App\MerchantBranch');
    }
}

2. Use a Hidden Attribute

If you want to avoid adding merchant_branch_id to the fillable list because it's technically an internal identifier managed by the relationship, you can use Laravel's $hidden array (in newer versions) or simply rely on the fact that relationships often don't need mass assignment for the key itself. However, updateOrCreate is stricter than create. It attempts to update all provided keys. If your intention is to only update the token column but let the foreign key remain untouched by the mass assignment window, you might prefer a direct query or adjusting the fillable array as shown above.

Why Your Original Code Worked

Your original implementation used $find = MerchantBranchToken::find($id). This bypasses the mass assignment protection entirely because you are assigning to a specific instance that has already been loaded from the database. When you call $find->save(), Laravel only updates the dirty attributes (the ones that changed since loading). You were manually setting properties and saving, which naturally respects your existing fillable constraints for those specific properties.

Trade-offs with updateOrCreate

The main advantage of switching to updateOrCreate is readability and efficiency. It generates a single SQL statement that checks existence (WHERE merchant_branch_id = ?) and updates or inserts in one go. Your current approach performs two queries: one SELECT to check existence, and then an INSERT or UPDATE depending on the result.

If you are dealing with high-concurrency environments, there is a theoretical race condition where two requests could see the record as missing at the same time. While unlikely for simple token updates, updateOrCreate handles this atomicity better because the check-and-insert happens within a single database transaction context managed by the ORM.

When to Stick with Your Current Approach

If your MerchantBranchToken model has many columns and you rarely want to update anything other than the token string itself, forcing merchant_branch_id into $fillable might expose that column to mass assignment vulnerabilities elsewhere in your application. In such cases, a direct query might be safer:

$exists = MerchantBranchToken::where('merchant_branch_id', $id)->first();

if (!$exists) {
    MerchantBranch::find($id)->token()->create(['token' => $token]);
} else {
    $exists->update(['token' => $token]);
}

This avoids the fillable headache but reintroduces the two-query pattern. Ultimately, if you can safely configure $fillable, updateOrCreate is the cleanest solution and aligns with Laravel's philosophy of leveraging Eloquent's built-in capabilities over manual conditional logic.

Our network