Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

untymage's avatar

Create or Attach

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 ...)

So how do you refactor above code?

0 likes
3 replies
mironmg's avatar
mironmg
Best Answer
Level 6
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();
2 likes

Please or to participate in this conversation.