Skip to content

Instantly share code, notes, and snippets.

@hosni
Created September 17, 2023 20:01
Show Gist options
  • Save hosni/153e570b02247217d8871f35ab4ef0d5 to your computer and use it in GitHub Desktop.
Save hosni/153e570b02247217d8871f35ab4ef0d5 to your computer and use it in GitHub Desktop.
Postgres: Unique violation: 7 ERROR: duplicate key value violates unique constraint
// Get all the tables from your database
$tables = \DB::select('SELECT table_name FROM information_schema.tables WHERE table_schema = \'public\' ORDER BY table_name;');
// Set the tables in the database you would like to ignore
$ignores = array('admin_setting', 'model_has_permissions', 'model_has_roles', 'password_resets', 'role_has_permissions', 'sessions');
//loop through the tables
foreach ($tables as $table) {
// if the table is not to be ignored then:
if (!in_array($table->table_name, $ignores)) {
//Get the max id from that table and add 1 to it
$seq = \DB::table($table->table_name)->max('id') + 1;
// alter the sequence to now RESTART WITH the new sequence index from above
\DB::select('ALTER SEQUENCE ' . $table->table_name . '_id_seq RESTART WITH ' . $seq);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment