Jackson J
Jackson J

Reputation: 1523

How to store log of all changes to Eloquent model in Laravel 5.4?

I want to store changes to all fields in Eloquent model into database.

I can do it using created and updated events but there is a problem with multiple foreign relations (described as separate tables).

Example:

User
    login
    Roles -> hasMany

When I update login field it is easy to write old and new value into database, but when I update Roles relation nothing happens.

How can I track all foreign relations (like hasMany, hasManyThrough, ManyToMany)?

Upvotes: 0

Views: 9911

Answers (2)

gthuo
gthuo

Reputation: 2566

Owen-it has a very nice Library called laravel-auditing, which keeps an easy to query list of all changes that are made to a model, and I think it does quite an awesome piece of work. Have used it and it is worth it to try out.

Upvotes: 4

LombaX
LombaX

Reputation: 17364

There is no embedded and simple method to do it.
Eloquent doesn't provide any method to implement observers on related models by design. Many proposal in this way have been rejected by Taylor (just one example).

The only thing you can do, is to create your own methods to do it. You have many possibilities, here are some of them in order of complexity (some of them are "dirty" :-)

  • add a created and updated observer on each related model
  • override the save() or create your own saveAndFire() method on your eloquent instances, and from that method retrieve the parent and call its log methods before saving. (this is a little bit "dirty" imho)
  • encapsulate all your persistence layer and fire events yourself on saving objects (look at the repository pattern, for example)

Upvotes: 1

Related Questions