Laravel eloquent ignores error while inserting duplicate key

I am retrieving JSON from another service and want to insert a bunch of data into the table. I want to make it so that it does not crash every time I run it. I would like to keep my unique restriction for my PC table (because I do not want to insert the same data twice), but I do not want laravel to give a fatal error if this happens (only in a specific table).

How can I insert my data and continue pasting if I try to insert other data with a duplicate primary key?

Schema::create('dummy', function (Blueprint $table) {
    $table->integer('id')->unique();

    $table->string('name',100);
});

Extract a bunch of JSON from another API. Then insert the whole line:

{ 
   'id':1,
    'name': 'one'
},{
    'id':2
    'name':'two'
}

what is he doing.

DB::table('dummy')->insert([
    ['id' => 1, 'name' => 'one'],
    ['id' => 2, 'name' => 'two']
]);

Then the next day, new data about the third-party API appears. And want to update my database:

select json and get:

{ 
   'id':1,
    'name': 'one'
},{
    'id':2
    'name':'two'
},{
    'id':3
    'name':'three'
}

what is he doing:

DB::table('dummy')->insert([
    ['id' => 1, 'name' => 'one'], // <-- will crash there cause PK already existe, but want to keep inserting
    ['id' => 2, 'name' => 'two'], // <-- skipp cause already exist
    ['id' => 3, 'name' => 'three'] // insert that line.
]);
+9
2

PDO

try 
{
    // inserting in DB;
}
catch(\Illuminate\Database\QueryException $e){
    // do what you want here with $e->getMessage();
}

, , DB:

public function insertInDB()
{
    DB::transaction(function () {
        DB::table(...);
        // if everything is fine, it will commit, else, it will rollback
    }
}
+4

, INSERT IGNORE , INSERT IGNORE, Laravel

0

Source: https://habr.com/ru/post/1677309/


All Articles