How to change insertion procedures of a model

Published 3 months ago by VortixDev

When one model inserts a new row into its table, I also want it to call upon another model to insert a new row into its table. Let me explain:

I have created three types of accounts, and each of these has a relationship with a central "BaseUser" model. This is necessary as certain information such as email address should be unique through all the accounts, so that a user of account type 1 cannot have the same email address as account type 2. This is made easier by the central "base table". Additionally is the reason of identifying the account type of the user, which is important for operations like password resets.

This means that when a user registers for account type 1, I also want the BaseUser model to create a new entry in its table. I have defined the relationship between this central model and all of the individual account type models, but I'm not sure if there is a simple way to define behavior for the insertion of data other than overriding save and firstOrCreate, and any other methods that may deal with the insertion of data.

Best Answer (As Selected By VortixDev)
tykus

Have a look at Model Events - you can hook into the creating or created Eloquent events on the first model, and create the BaseUser instance whenever the first model is created.

tykus
tykus
3 months ago (284,500 XP)

Have a look at Model Events - you can hook into the creating or created Eloquent events on the first model, and create the BaseUser instance whenever the first model is created.

Snapey
Snapey
3 months ago (527,165 XP)

You can hook into eloquent events, in this case the created event.

You may also want to consider delete events also.

https://laravel.com/docs/5.4/eloquent#events

VortixDev

Looks perfect, thank you both!

Sign In or create a forum account to participate in this discussion.