using firstOrCreate on relationship cause error

Posted 1 week ago by untymage

Say i have many-to-many relationship with Thread and Tag

Thread.php

When i try to use $this->tags()->firstOrCreate :

public function addTags($name)
{
        $tag = $this->tags()->firstOrCreate(compact('name'));

        $this->tags()->attach($tag->id);

}

it cuase error:

SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: thread_tag.thread_id, thread_tag.tag_id (SQL: insert into "thread_tag" ("thread_id", "tag_id") values (1, 1))

Please sign in or create an account to participate in this conversation.