I'm fetching a JSON from another service and want to insert a bunch of data in a table. I want to do it a way it won't crash everytime I run it. I'd like to keep my unique constraint on my PK of the table, (cause i dont want to insert the same data twice) but, I don't want laravel to throw a fatal error if it happens (on a specific table only).
How can I insert my datas, and continue to insert if I try to insert another data with a duplicate primary key?
Schema::create('dummy', function (Blueprint $table) {
$table->integer('id')->unique();
$table->string('name',100);
});
Fetch a bunch of JSON from another API. Then inserting all row:
{
'id':1,
'name': 'one'
},{
'id':2
'name':'two'
}
that makes.
DB::table('dummy')->insert([
['id' => 1, 'name' => 'one'],
['id' => 2, 'name' => 'two']
]);
Then another day, there are new data on the 3rd party API. And want to update my database:
fetch the json, and receives:
{
'id':1,
'name': 'one'
},{
'id':2
'name':'two'
},{
'id':3
'name':'three'
}
that makes :
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.
]);