Al_ Al_ - 1 year ago 105
PHP Question

Preventing Laravel adding multiple records to a pivot table

I have a many to many relationship set up and working, to add an item to the cart I use:


Which adds an item to the pivot table (as it should), but if the user clicks on the link again to add an item they have already added it creates a duplicate entry in the pivot table.

Is there a built in way to add a record to a pivot table only if one does not already exist?

If not, how can I check the pivot table to find if a matching record already exists?

Answer Source

As explained here few months ago, there is not built in function to protect you against a doublet in your pivot table. The main reason is because it exists functional cases when you could want to save two similar records in your pivot table.

You can write a very simple condition like this one :

if (!$cart->items->contains($newItem->id)) {

Or/and you can add unicity condition in your database, it would throw an exception during an attempt of saving a doublet.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download