5 Benefits Of Having A Developer Journal
April 16, 2021Router Extra Options
May 4, 2021
I recently had the task of keeping track of a User’s status in a Log table. Instead of creating new Logs all over the application, making use of Observers made more sense. With Observers, we are able to group all the Model Event Listeners into the same class. Every time a User’s data was added or updated, or even deleted, I was able to make use of the Observers to store the changes in the Log.
Setup
The first thing we need to do is create the Observer.
php artisan make:observer UserObserver --model=User
This will create a new app\Observers\UserObserver.php
file with the created
, updated
, deleted
, restored
and forceDeleted
functions added by default.
Next we have to Register the UserObserver
inside the app/Providers/AppServiceProvider.php
boot function.
Usage
In the above example, the events will fire whenever the User Model is saved, updated, deleted, etc.
1 Comment
This is really interesting, I have used a package before called laravel-auditing, which does exactly this, but its great to see a coded implementation of this.