PHP code example of guidocella / eloquent-insert-on-duplicate-key

1. Go to this page and download the library: Download guidocella/eloquent-insert-on-duplicate-key library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

guidocella / eloquent-insert-on-duplicate-key example snippets


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
    ));
});

InsertOnDuplicateKey\InsertOnDuplicateKeyServiceProvider::class,

$data = [
    ['id' => 1, 'name' => 'name1', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'name2', 'email' => '[email protected]'],
];

User::insertOnDuplicateKey($data);

User::insertIgnore($data);

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

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

User::insertOnDuplicateKey([
    'id'       => 1,
    'name'     => 'created user',
    'email'    => '[email protected]',
    'password' => 'secret',
], ['name' => 'updated user', 'email']);

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

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

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