Support the ongoing development of Laravel.io →
Database Eloquent

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.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

screenager screenager Joined 12 Jan 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.