Creating and Update Laravel Eloquent

Creating and Update Laravel Eloquent

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

Stefan Bogdanescu

Founder & Senior Architect

The Shorthand for Insert or Update in Laravel

Developers frequently encounter the pattern of "upsert": inserting a new record if it doesn't exist, or updating an existing one if it does. The source material illustrates this common scenario using a manual conditional check. You query for a specific ShopMeta record based on shopId and metadataKey. If the result is null, you prepare to insert. If the result exists, you prepare to update. While this logic is sound, it introduces friction into your codebase. It requires explicit branching logic, multiple queries in some implementations, or at least a mental overhead of managing state between the database and your application memory.

Laravel provides a dedicated Eloquent method to handle this exact pattern without the verbosity of if/else blocks. The solution is the createOrFirst() method (or its alias updateOrCreate, depending on your specific intent, though createOrFirst is often preferred for strict "insert or update" semantics).

Consider the scenario where you are managing shop metadata. Instead of fetching a record solely to check if it exists, you can instruct Eloquent to attempt an insertion first. If the primary key already exists in the table, that existing row is returned and updated with the new data. If it does not exist, a fresh record is created and returned.

Here is how you refactor the manual logic into a single, atomic operation:

$shopOwner = ShopMeta::updateOrCreate(
    ['shopId' => $theID, 'metadataKey' => 2001],
    [
        'value' => $newMetadataValue, // Your actual data payload here
        'created_at' => now(),
        'updated_at' => now(),
    ]
);

// Logic for the new or updated record continues here
if ($shopOwner->isNew) {
    // Handle new record logic
} else {
    // Handle update logic
}

The updateOrCreate method accepts the attributes used to determine uniqueness as the first argument and the data to be inserted or merged into the existing row as the second. In this example, we use shopId and metadataKey as the unique identifiers. If a row matches these keys, Eloquent updates it; otherwise, it inserts.

A critical technical detail involves how you handle timestamps. When using updateOrCreate, the updated_at column will automatically update on an existing row if it is present in the data array passed to the method. However, if you are relying on the created_at timestamp to distinguish between a new and an old record, be aware of its behavior. If the model uses auto-incrementing IDs or UUIDs, you generally don't need to worry about collision, but if you rely on timestamps for business logic (like auditing), ensure your data array includes them explicitly when updating, or configure your model's $dates property appropriately.

There is an alternative approach using createOrFirst(). This method is semantically closer to "insert first, then update". It attempts to insert the record. If a duplicate key violation occurs (assuming you have unique indexes set up), it catches that exception and performs an update instead. While functionally similar to updateOrCreate in many cases, createOrFirst offers slightly more control over which columns trigger the uniqueness constraint check versus which are simply updated.

However, the most robust approach often depends on your database constraints. If you have a unique index on shopId and metadataKey, both methods work efficiently. Without such an index, relying on application-level checks like createOrFirst might lead to race conditions where two concurrent requests try to insert the same record simultaneously, resulting in duplicate key errors that must be caught and handled.

Ultimately, leveraging Eloquent's built-in upsert functionality removes the need for manual queries and conditional branching. It makes your code more readable, reduces the likelihood of query injection vulnerabilities inherent in raw SQL upserts, and ensures consistent behavior across different database backends supported by Laravel.

Our network