Laravel Polymorphic many to many relationship issue

68 views Asked by At

I have a Many to Many Polymorphic relationship setup between a few models and everything seems to be working just fine with one slight issue...

If I add the same relation $book->genres()->save($scifi) multiple times, it shows up multiple times in my database. Maybe this is intentional, maybe it's not. If I'm overlooking something, I'd like to have it working the "Laravel" way before I go and start making methods to ensure that only one relationship of that kind is in the DB at a time.

1

There are 1 answers

0
pinkal vansia On BEST ANSWER

use sync. It will synchronize rather than duplicating it.

$book->genres()->sync([$scifi->id], false);

Read More

Don't forget false as second argument, or it will detach all previous association.