Laravel insert or update multiple rows

Laravel insert or update multiple rows

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

Stefan Bogdanescu

Founder & Senior Architect

Laravel insert or update multiple rows

When managing a navigation tree with drag-and-drop functionality, you often end up with a complete snapshot of the new structure in memory. You have an array of models where each item contains its new position data, including _lft, _right, and parent_id. The goal is to apply this entire set of changes to the database in a single atomic operation, rather than iterating through the array with a foreach loop. This approach is necessary because updating tree positions individually can lead to race conditions or inconsistent state if other requests modify the tree between operations.

The standard updateOrCreate method in Laravel is designed for row-level operations. It takes a single model instance (or an array representing one) and updates it only if a matching primary key exists, or creates it if it does not. Attempting to pass multiple arrays to this method, such as Navigation::updateOrCreate([...], [...]), will not work as intended because the underlying Eloquent query builder expects a singular condition set for the existence check and a singular update payload.

To handle bulk inserts or updates efficiently in Laravel 6 and later, you should utilize the upsert functionality introduced in the Query Builder. This method allows you to specify the column(s) that define uniqueness (typically your primary key, like id) and provide an array of data rows. If a row with the specified unique keys exists, it will be updated; otherwise, it will be inserted.

Here is how you can apply this to your navigation tree scenario:

$updates = [
    ['id' => 1, 'name' => 'Home', 'parent_id' => 0],
    ['id' => 2, 'name' => 'Products', 'parent_id' => 1],
    ['id' => 3, 'name' => 'Services', 'parent_id' => 1],
];

Navigation::upsert(
    $updates,
    ['id'], // The unique key(s) used to determine if a row should be updated or inserted
    ['name', 'parent_id', '_lft', '_right'] // The columns to update. 
                                             // Note: 'id' is excluded here as it's usually the primary key
);

In this example, the first argument $updates contains your full dataset. The second argument ['id'] tells Laravel which column acts as the unique identifier for the merge operation. The third argument defines the specific columns that should be overwritten. It is crucial to exclude the primary key (id) from the update columns list unless you specifically intend to change it, as doing so might trigger unexpected behavior depending on your database constraints and Eloquent model configuration.

However, there is a significant trade-off when using upsert with tree structures that rely on self-referencing relationships or specific ordering columns like _lft and _right. If your navigation table has unique constraints on these positioning columns, the upsert operation might fail if the incoming data conflicts with existing unique indices that are not part of the merge key definition. Additionally, standard database triggers often used to maintain tree integrity (like calculating _lft/_right automatically) might not fire correctly during an upsert depending on how your migration defined those constraints.

If you are using Laravel 8 or later, you can also consider using the insertOrIgnore method if you want to prioritize inserting new rows and ignoring updates for existing ones, though this is less common for tree structures where precise updates are required. For older versions of Laravel, a raw query approach using DB::table('navigation')->upsert(...) offers similar functionality without relying on the model's magic methods.

The primary advantage of this approach over a loop is performance and consistency. By sending one query to the database, you reduce network round-trips and ensure that the transaction either fully succeeds or fully rolls back if an error occurs within the upsert call. This atomicity is essential for maintaining the integrity of hierarchical data structures where the position of every node relative to its parent matters.

For more complex scenarios involving deep tree manipulations, you might need to check specific community resources like https://laravelcompany.com for advanced migration patterns or custom upsert strategies tailored to nested sets or materialized paths.

Our network