PHPackages                             yadakhov/insert-on-duplicate-key - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. yadakhov/insert-on-duplicate-key

ActiveLibrary[Database &amp; ORM](/categories/database)

yadakhov/insert-on-duplicate-key
================================

A trait for MySQL INSERT ON DUPLICATE KEY UPDATE.

v1.3.0(5y ago)2762.9M↑12.8%52[9 issues](https://github.com/yadakhov/insert-on-duplicate-key/issues)[2 PRs](https://github.com/yadakhov/insert-on-duplicate-key/pulls)6MITPHP

Since May 13Pushed 4y ago11 watchersCompare

[ Source](https://github.com/yadakhov/insert-on-duplicate-key)[ Packagist](https://packagist.org/packages/yadakhov/insert-on-duplicate-key)[ Docs](https://github.com/yadakhov/insert-on-duplicate-key)[ RSS](/packages/yadakhov-insert-on-duplicate-key/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (16)Used By (6)

MySQL Insert On Duplicate Key Update Eloquent Trait
===================================================

[](#mysql-insert-on-duplicate-key-update-eloquent-trait)

[![Latest Stable Version](https://camo.githubusercontent.com/f3df2e9cd813595e40d890dc550b785fdb3f60dad4cd90d3981dea71b89746b0/68747470733a2f2f706f7365722e707567782e6f72672f796164616b686f762f696e736572742d6f6e2d6475706c69636174652d6b65792f76657273696f6e)](https://packagist.org/packages/yadakhov/insert-on-duplicate-key)[![License](https://camo.githubusercontent.com/b714fe2d4a39841a45fee78cdd0d7a86cdf95cab9eab508135c7fdfc0bbed04e/68747470733a2f2f706f7365722e707567782e6f72672f796164616b686f762f696e736572742d6f6e2d6475706c69636174652d6b65792f6c6963656e7365)](https://packagist.org/packages/yadakhov/insert-on-duplicate-key)[![Build Status](https://camo.githubusercontent.com/0138cb6df72e44b3f4b341eae4eee5786baeaad86089a87bf58b9620cf1108f9/68747470733a2f2f7472617669732d63692e6f72672f796164616b686f762f696e736572742d6f6e2d6475706c69636174652d6b65792e737667)](https://travis-ci.org/yadakhov/insert-on-duplicate-key)

[Insert Duplicate Key Update](http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html) is a quick way to do mass insert.

It's a trait meant to be used with Laravel's Eloquent ORM.

### Code Example

[](#code-example)

```
use Illuminate\Database\Eloquent\Model;
use Yadakhov\InsertOnDuplicateKey;

/**
 * Class User.
 */
class User extends Model
{
    // The function is implemented as a trait.
    use InsertOnDuplicateKey;
}
```

#### Multi values insert.

[](#multi-values-insert)

```
    $users = [
        ['id' => 1, 'email' => 'user1@email.com', 'name' => 'User One'],
        ['id' => 2, 'email' => 'user2@email.com', 'name' => 'User Two'],
        ['id' => 3, 'email' => 'user3@email.com', 'name' => 'User Three'],
    ];
```

Important: the order of the keys are important. It should be the same for every arrays. The reason is the code uses `array_values()`.

Do not do this:

```
    $users = [
        ['id' => 1, 'email' => 'user1@email.com', 'name' => 'User One'],
        ['email' => 'user2@email.com', 'id' => 2, 'name' => 'User Two'],
        ['email' => 'user3@email.com', 'name' => 'User Three', 'id' => 3],
    ];
```

#### INSERT ON DUPLICATE KEY UPDATE

[](#insert-on-duplicate-key-update)

```
    User::insertOnDuplicateKey($users);
```

```
    -- produces this query
    INSERT INTO `users`(`id`,`email`,`name`) VALUES
    (1,'user1@email.com','User One'), (2,'user3@email.com','User Two'), (3,'user3email.com','User Three')
    ON DUPLICATE KEY UPDATE `id` = VALUES(`id`), `email` = VALUES(`email`), `name` = VALUES(`name`)
```

```
    User::insertOnDuplicateKey($users, ['email']);
```

```
    -- produces this query
    INSERT INTO `users`(`id`,`email`,`name`) VALUES
    (1,'user1@email.com','User One'), (2,'user3@email.com','User Two'), (3,'user3email.com','User Three')
    ON DUPLICATE KEY UPDATE `email` = VALUES(`email`)
```

If users have a numeric column we would like, for example, to sum:

```
    $users = [
        ['id' => 1, 'name' => 'User One', 'heritage' => 1000],
        ['id' => 2, 'name' => 'User Two', 'heritage' => 2000],
        ['id' => 3, 'name' => 'User Three', 'heritage' => 1500],
    ];
```

```
    User::insertOnDuplicateKey($users, ['heritage' => DB::raw('`heritage` + VALUES(`heritage`)')]);
```

```
    -- produces this query
    INSERT INTO `users`(`id`,`email`,`name`) VALUES
    (1,'user1@email.com','User One'), (2,'user3@email.com','User Two'), (3,'user3email.com','User Three')
    ON DUPLICATE KEY UPDATE `heritage` = `heritage` + VALUES(`heritage`)
```

#### INSERT IGNORE

[](#insert-ignore)

```
    User::insertIgnore($users);
```

```
    -- produces this query
    INSERT IGNORE INTO `users`(`id`,`email`,`name`) VALUES
    (1,'user1@email.com','User One'), (2,'user3@email.com','User Two'), (3,'user3email.com','User Three');
```

#### REPLACE INTO

[](#replace-into)

```
    User::replace($users);
```

```
    -- produces this query
    REPLACE INTO `users`(`id`,`email`,`name`) VALUES
    (1,'user1@email.com','User One'), (2,'user3@email.com','User Two'), (3,'user3email.com','User Three');
```

### created\_at and updated\_at fields.

[](#created_at-and-updated_at-fields)

created\_at and updated\_at will *not* be updated automatically. To update you can pass the fields in the insert array.

```
['id' => 1, 'email' => 'user1@email.com', 'name' => 'User One', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]
```

### Run unit tests

[](#run-unit-tests)

```
./vendor/bin/phpunit

```

### Will this work on Postgresql?

[](#will-this-work-on-postgresql)

No. On Duplicate Key Update is only available on MySQL. Postgresql 9.4 has a similar feature called [UPSERT](https://wiki.postgresql.org/wiki/UPSERT). Implementing UPSERT is left as an exercise for the reader.

### Isn't this the same as updateOrCreate()?

[](#isnt-this-the-same-as-updateorcreate)

It is similar but not the same. The updateOrCreate() will only work for one row at a time which doesn't allow bulk insert. InsertOnDuplicateKey will work on many rows.

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity60

Solid adoption and visibility

Community29

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 79.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~127 days

Recently: every ~388 days

Total

15

Last Release

1873d ago

Major Versions

v0.0.10 → v1.0.02017-01-01

v0.1.0 → v1.1.02017-01-19

### Community

Maintainers

![](https://www.gravatar.com/avatar/7e2a2bbdfd6287c649a9759274fbd47d769ea78bf09b03ee3dcefe42790a95d4?d=identicon)[yadakhov](/maintainers/yadakhov)

---

Top Contributors

[![yadakhov](https://avatars.githubusercontent.com/u/146636?v=4)](https://github.com/yadakhov "yadakhov (23 commits)")[![votemike](https://avatars.githubusercontent.com/u/3957065?v=4)](https://github.com/votemike "votemike (2 commits)")[![alberto-bottarini](https://avatars.githubusercontent.com/u/1442934?v=4)](https://github.com/alberto-bottarini "alberto-bottarini (1 commits)")[![hibob224](https://avatars.githubusercontent.com/u/3732875?v=4)](https://github.com/hibob224 "hibob224 (1 commits)")[![jstoks](https://avatars.githubusercontent.com/u/2073157?v=4)](https://github.com/jstoks "jstoks (1 commits)")[![kkomelin](https://avatars.githubusercontent.com/u/755066?v=4)](https://github.com/kkomelin "kkomelin (1 commits)")

---

Tags

databasemysqleloquent

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/yadakhov-insert-on-duplicate-key/health.svg)

```
[![Health](https://phpackages.com/badges/yadakhov-insert-on-duplicate-key/health.svg)](https://phpackages.com/packages/yadakhov-insert-on-duplicate-key)
```

###  Alternatives

[pecee/pixie

Lightweight, fast query-builder for PHP based on Laravel Eloquent but with less overhead.

4128.7k8](/packages/pecee-pixie)[rah/danpu

Zero-dependency MySQL dump library for easily exporting and importing databases

64401.8k10](/packages/rah-danpu)[moloquent/moloquent

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

120114.6k7](/packages/moloquent-moloquent)[sarfraznawaz2005/indexer

Laravel package to monitor SELECT queries and offer best possible INDEX fields.

562.7k](/packages/sarfraznawaz2005-indexer)[zara-4/laravel-lazy-mysql

A lazy mysql based Eloquent model and Query builder for Laravel

127.9k](/packages/zara-4-laravel-lazy-mysql)[jrsaunders/shard-matrix

A Complete Database Sharding system for MYSQL and/or Postgres. Using Laravels Query Builder easily scale up your application. Configure your whole solution in one Yaml Config file.

271.5k](/packages/jrsaunders-shard-matrix)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
