Use sync() or attach() / detach() https://laravel.com/docs/5.8/eloquent-relationships#updating-many-to-many-relationships
Next time use google or the documentation :) they both are pretty good.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have Many to many relationship with Tag and Thread Model, Here is what i tried for creating or attaching :
Tag.php:
public static function searchByName($name)
{
return self::where('name', $name)->get()->first();
}
Thread.php :
public function addTags($tags)
{
$attributes = explode(',', $tags);
foreach ($attributes as $name) {
if ( $tag = Tag::searchByName($name) ) {
$this->tags()->attach($tag->id);
continue;
}
$this->tags()->create(compact('name'));
}
return;
}
I set up a static method in Tag model for checking tag by name (searchByName) if the tag exist then only attach to the new Thread otherwise create a new tag, I think this approach is not clean , because for every many to many relationship i do this way (creating seach method in model and ...)
public function addTags($tags)
{
$attributes = explode(',', $tags);
foreach ($attributes as $name) {
$tag = Tag::firstOrCreate(['name' => $name])
$this->tags()->syncWithoutDetaching([$tag->id]);
}
return;
}
and you can also delete the searchByName method ... You can use the whereName for it
Tag::whereName($name)->first();
Please or to participate in this conversation.