I am in the midst of writing a command in my Laravel project which inserts categories to a database table, but depending on whether or not they already exist.
I investigated the way to do this and came across firstOrCreate
method, so I wrote the following in my command:
$comCats = new CommunicationsCategories();
$comCats->firstOrCreate(
['name' => 'Job Updates'], ['region_id' => 1]);
$comCats->firstOrCreate(
['name' => 'Alerts'], ['region_id' => 1]);
Basically, I need to create these two categories in the communications_categories table with a region ID of 1. The Job Updates category already exists, so it skipped that as expected but when it tries to create the Alerts category which doesn't exist I get the following error in my console:
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "communications_categories_pkey"
DETAIL: Key (id)=(2) already exists. (SQL: insert into "communications_categories" ("name", "region_id", "updated_at", "created_at") values (Alerts, 1, 2018-06-19 09:38:20, 2018-06-19 09:38:20) returning "id")
It appears that it's trying to allocate a primary key ID of 2 when it already exists - but the table structure has a nextval on the primary key which I thought would take the last ID added and create a new one after that. According to the Laravel documentation on Eloquent Inserts here there's no mention of having to stipulate the actual primary key id itself, and the fillable elements are only name
and region_id
.
Any help on this appreciated, as I'm reasonably new to Laravel and the eloqent database methods. If it helps, I'm using a PostgreSQL database.