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

ronon's avatar
Level 9

Save additional columns in Many To Many Polymorphic relation?

I have a similiar many to many plymorhpic structure to this

posts
    id - integer
    name - string

videos
    id - integer
    name - string

tags
    id - integer
    name - string

taggables
    tag_id - integer
    taggable_id - integer
    taggable_type - string
   /*  CUSTOM  */
    custom_entry - string
    priority - integer

expect I have two additional columns in taggables, custom_entry and priority. How can I fill those two columns with Eloquent?

I tried to manipulate the $tag value and added

$tag->custom_entry = "Random string";
$tag->priority = 1;
$video->tags()->save($tag);

but if I try to save I receive an error that those two columns are missing in my tags table. So how can I insert them in taggables table?

0 likes
3 replies
ronon's avatar
ronon
OP
Best Answer
Level 9

Solved it, just had to use a second array with the needed attributes.

->save($tag, [priority => 1]);
1 like
burlresearch's avatar

Typically with many/many relations - you want to 'attach' instead of 'save' the relationships:

$video->tags()->attach($t, ['custom'=>'custstring','priority'=>2])
ronon's avatar
Level 9

Whats the difference? If I use saveMany(ModelCollection, attributeArray) it works, but I don't have a clue how to do it with attach.

Please or to participate in this conversation.