I have a many to many relationship set up and working, to add an item to the cart I use:
$cart->items()->attach($item);
Which adds an
There are some great answers posted already. I wanted to throw this one out here as well though.
The answers from @AlexandreButynski and @Barryvdh are more readable than my suggestion, what this answer adds is some efficiency.
It retrieves only the entries for the current combination (actually only the id) and it than attaches it if it does not exist. The sync method (even without detaching) retrieves all currently attached ids. For smaller sets with little iterations this will hardly be a difference, ... you get my point.
Anyway, it is definitely not as readable, but it does the trick.
if (is_null($book->authors()->find($author->getKey(), [$author->getQualifiedKeyName()])))
$book->authors()->attach($author);