PHPackages                             terranc/eloquent-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. terranc/eloquent-insert-on-duplicate-key

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

terranc/eloquent-insert-on-duplicate-key
========================================

Macros for INSERT ON DUPLICATE KEY UPDATE and INSERT IGNORE with Eloquent

1.1.1(8mo ago)01.7k↓25%MITPHPPHP &gt;=5.6.4

Since Sep 12Pushed 8mo agoCompare

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

READMEChangelog (4)Dependencies (3)Versions (7)Used By (0)

Laravel Insert On Duplicate Key And Insert Ignore
=================================================

[](#laravel-insert-on-duplicate-key-and-insert-ignore)

This package is deprecated because `upsert` and `insertOrIgnore` have been added to Laravel.

If you need the pivot functions, they are trivial to implement:

```
BelongsToMany::macro('attachUpsert', function ($id, array $attributes = []) {
    $this->newPivotStatement()->upsert($this->formatAttachRecords(
        $this->parseIds($id),
        $attributes
    ), null);
});

BelongsToMany::macro('attachOrIgnore', function ($id, array $attributes = []) {
    $this->newPivotStatement()->insertOrIgnore($this->formatAttachRecords(
        $this->parseIds($id),
        $attributes
    ));
});
```

This package provides macros to run INSERT ... ON DUPLICATE KEY UPDATE and INSERT IGNORE queries on models and pivot tables with Laravel's ORM Eloquent using MySql or MariaDB.

Installation
------------

[](#installation)

Install this package with composer.

```
composer require guidocella/eloquent-insert-on-duplicate-key
```

If you don't use Package Auto-Discovery yet add the service provider to your Package Service Providers in `config/app.php`.

```
InsertOnDuplicateKey\InsertOnDuplicateKeyServiceProvider::class,
```

Usage
-----

[](#usage)

### Models

[](#models)

Call `insertOnDuplicateKey` or `insertIgnore` from a model with the array of data to insert in its table.

```
$data = [
    ['id' => 1, 'name' => 'name1', 'email' => 'user1@email.com'],
    ['id' => 2, 'name' => 'name2', 'email' => 'user2@email.com'],
];

User::insertOnDuplicateKey($data);

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

#### Customizing the ON DUPLICATE KEY UPDATE clause

[](#customizing-the-on-duplicate-key-update-clause)

##### Update only certain columns

[](#update-only-certain-columns)

If you want to update only certain columns, pass them as the 2nd argument.

```
User::insertOnDuplicateKey([
    'id'    => 1,
    'name'  => 'new name',
    'email' => 'foo@gmail.com',
], ['name']);
// The name will be updated but not the email.
```

##### Update with custom values

[](#update-with-custom-values)

You can customize the value with which the columns will be updated when a row already exists by passing an associative array.

In the following example, if a user with id = 1 doesn't exist, it will be created with name = 'created user'. If it already exists, it will be updated with name = 'updated user'.

```
User::insertOnDuplicateKey([
    'id'    => 1,
    'name'  => 'created user',
], ['name' => 'updated user']);
```

The generated SQL is:

```
INSERT INTO `users` (`id`, `name`) VALUES (1, "created user") ON DUPLICATE KEY UPDATE `name` = "updated user"
```

You may combine key/value pairs and column names in the 2nd argument to specify the columns to update with a custom literal or expression or with the default `VALUES(column)`. For example:

```
User::insertOnDuplicateKey([
    'id'       => 1,
    'name'     => 'created user',
    'email'    => 'new@gmail.com',
    'password' => 'secret',
], ['name' => 'updated user', 'email']);
```

will generate

```
INSERT INTO `users` (`id`, `name`, `email`, `password`)
VALUES (1, "created user", "new@gmail.com", "secret")
ON DUPLICATE KEY UPDATE `name` = "updated user", `email` = VALUES(`email`)
```

### Pivot tables

[](#pivot-tables)

Call `attachOnDuplicateKey` and `attachIgnore` from a `BelongsToMany` relation to run the inserts in its pivot table. You can pass the data in any of the formats accepted by `attach`.

```
$pivotData = [
    1 => ['expires_at' => Carbon::today()],
    2 => ['expires_at' => Carbon::tomorrow()],
];

$user->roles()->attachOnDuplicateKey($pivotData);

$user->roles()->attachIgnore($pivotData);
```

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance59

Moderate activity, may be stable

Popularity18

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 87.5% 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 ~215 days

Recently: every ~269 days

Total

6

Last Release

261d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e7a6d99f98f7816b74eaeb19e965fc77ff2647e506e4317fa3cbe1162dc65a37?d=identicon)[terranc](/maintainers/terranc)

---

Top Contributors

[![guidocella](https://avatars.githubusercontent.com/u/11783568?v=4)](https://github.com/guidocella "guidocella (63 commits)")[![terranc](https://avatars.githubusercontent.com/u/224353?v=4)](https://github.com/terranc "terranc (6 commits)")[![martianoff](https://avatars.githubusercontent.com/u/7222812?v=4)](https://github.com/martianoff "martianoff (2 commits)")[![thiagopromano](https://avatars.githubusercontent.com/u/2577646?v=4)](https://github.com/thiagopromano "thiagopromano (1 commits)")

---

Tags

laraveldatabasemysqleloquent

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k25.2M34](/packages/kirschbaum-development-eloquent-power-joins)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[mvanduijker/laravel-transactional-model-events

Add eloquent model events fired after a transaction is committed or rolled back

75164.5k](/packages/mvanduijker-laravel-transactional-model-events)[guidocella/eloquent-populator

Guess attributes for Eloquent model factories

7661.6k2](/packages/guidocella-eloquent-populator)

PHPackages © 2026

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