Laravel First or Create Throws Unique Violation Error

If you are using Laravel’s firstOrCreate() method and get a unique id violation error, there is a chance you have repopulated your database retroactively in Postgres. Postgres triggers the next id in the sequence on row creation instead of on import. So it thinks the next sequence in the id field is an existing ID therefore throws an error.

To set the next id in the sequence use the following query.

SELECT setval('users_id_seq', (SELECT MAX(id) from "users"));

Remember to change users to your table name (example: ‘roles_id_seq’ and ‘roles’).

Leave a Comment