Al_ Al_ - 3 months ago 25
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:

$cart->items()->attach($item);


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

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)) {
    $cart->items()->save($newItem);
}

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