Victor
Victor

Reputation: 5353

How to fire an update event when updating one to one relationships in Laravel?

I have two entities:

  1. Person
  2. Employee

Person hasOne Employee. Employee belongsTo Person.

Generally speaking, my task is: when person data changes, I need to make a copy of the model in revisions table. Each Person also hasMany PersonRevision. Kind of log of updating persons, which is used in many places in our application.

Technically, I separated Person and Employee, because not every person is employee and employee has a lot of additional columns.

So, the question is: when I update Person and do not touch its attributes but update the employee (which belongs to the person) attributes, the Update event does not fire in PersonObserver. And that's true since Person attributes has not been changed.

But

  1. I consider Employee as a part of Person, separated one to one in order to keep persons (which are not employees) table clean
  2. Every time person attributes or its employee attributes updated I need to create 2 revisions: person & employee. For this purpose I want to use Event Observers

So, how can I do this?

Upvotes: 0

Views: 1808

Answers (1)

Pavel Lint
Pavel Lint

Reputation: 3527

The quickest way for you in this situation is to create a listener for employee.updated event and trigger person.updated event inside it. So each time an Employee is updated, it automatically triggers Person update. You can then go further and check which fields are updated, and if those are only fields related to Employee and none related to Person, then NOT trigger the person.update event.

Upvotes: 1

Related Questions