Skip to content
A trait for MySQL INSERT ON DUPLICATE KEY UPDATE with Eloquent.
PHP
Branch: master
Clone or download

Latest commit

Fetching latest commit…
Cannot retrieve the latest commit at this time.

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
tests
.gitignore
.travis.yml
LICENSE.txt
composer.json
phpunit.xml
readme.md

readme.md

MySQL Insert On Duplicate Key Update Eloquent Trait

Insert Duplicate Key Update is a quick way to do mass insert.

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

Code Example

use Illuminate\Database\Eloquent\Model;
use TalentAsia\InsertOnDuplicateKey;

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

Multi values insert.

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

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`)

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

    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 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

./vendor/bin/phpunit

Will this work on Postgresql?

No. On Duplicate Key Update is only available on MySQL.

You can’t perform that action at this time.