benefits of developer journal

5 Benefits Of Having A Developer Journal

April 16, 2021
router extra options

Router Extra Options

May 4, 2021

Laravel Observers

April 26, 2021 / Taylor Plaatjies

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.

Share

Taylor Plaatjies

Laravel Observers
This website uses cookies to improve your experience. By using this website you agree to our Data Protection Policy.
Read more