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

Charrua's avatar

Many To Many Relationships attach/sync the same model

Hello, I'm working on an invoicing app. I have my Invoice and Product models.

In my DB I have a salables table that holds the relationship between Invoices and Products, in this case I'm using many to many polymorphic relationship, as I have also other models, like Budgets, etc.

So in that table I would save the products that are in the invoice or in the budget, as other data, as quantity, price, etc....

The problem is that when I save the invoice and attach products to the salables table, they do not appear to be saved.

Example, if I send product ID 1,2,3,4, each with internal data as quantity, there is no problem. To save I'm using $invoice->products()->attach($items);

The main issue, is when in the same invoice, I have for example the same product two times, ID 1 and ID 1, but with different quantities or prices... The problem is that it only saves one copy of the product.

That is because to save the related models, Laravel uses ID as key inside the array I'm passing to the attach() method. Is there other way to achieve this? any ideas?

0 likes
1 reply
deansatch's avatar

Sounds like you need to rethink the relationship. So you are saying you want to attach a product to an invoice several times with a pivot table? That would result in a table like:


Invoice_id    Product_id

1                    3

1                    3

Which would be pointless. No way to query it. I think you need more of an “invoice_item” relationship and invoice hasMany invoice_item, and invoice_item hasOne product

Please or to participate in this conversation.