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

VortixDev's avatar

How to interlink table insertions

When an entry is inserted in one table (let's call it "table 1"), I want an entry to be inserted into another table as well (let's call it "table 2") (I actually want to have data inserted into one of three potential tables depending on certain information, which is why it's not all under one table). From what I understand, the best way to do this is to create an observer to listen for the "creating/created" events and insert a row into "table 2" when that event occurs. I'm hoping there's an easy way to ensure that if the insertion I control for "table 2" fails, I can prevent the entry to "table 1" which is occuring under the "creating" event from being created as well. Is there an ideal way to do this?

0 likes
2 replies
jlrdw's avatar

Why can't you use a switch statement to handle it depending on the condition or even an if statement.

tykus's avatar

Have a look at database transactions which will allow you to rollback a set of queries if one fails. I am not 100% sure if a transaction will work across Eloquent model events however; I remember something changed between 5.1(?) and 5.2(?), but could be wrong.

Please or to participate in this conversation.