Suppose you have a many-to-many relation between two models, let's say Post and Tag, and you want to add multiple tags to a post, you could use this construction:
foreach ($tags as $tag) {
if (!$post->tags->contains($tag->id)) {
$post->tags()->attach($tag);
}
}
However, suppose you somehow have managed to get duplicates in your $tags array (elements with the same ID). In that case, I found out that in the foreach step for the duplicate element, the contains() method will return false, even if the pivot record is already saved in the database. This will of course result in a mysql error when attaching the duplicate tag.
How can this be avoided? Looks like the contains() method only looks into the parent model which hasn't refreshed its $tags property?
Alternatively, working with the sync() method, or first cleaning up the duplicates before attaching to the parent model are workarounds.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community