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.
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
forceDeleted functions added by default.
Next we have to Register the
UserObserver inside the
app/Providers/AppServiceProvider.php boot function.
In the above example, the events will fire whenever the User Model is saved, updated, deleted, etc.