Why we need the Laravel Observer?
If you want to perform some actions while your Eloquent model is processing. Then, Laravel Observers are a convenient way to do this.
List of events given below, which we used in the Observer class:
- retrieved- after a record has been retrieved.
- creating- before a record has been created.
- created- after a record has been created.
- updating- before a record is updated.
- updated- after a record has been updated.
- saving- before a record is saved (either created or updated).
- saved- after a record has been saved (either created or updated).
- deleting- before a record is deleted or soft-deleted.
- deleted- after a record has been deleted or soft-deleted.
- restoring- before a soft-deleted record is going to be restored.
- restored- after a soft-deleted record has been restored.
- forceDeleted- handle the “force deleted” event
Observers
Observers are used to group event listeners for a model. Observers classes method names refer to the Eloquent event you want to listen for. These methods receive the model as their only argument.
You can use model events that are fired automatically by laravel when the new record is created, updated or deleted.
Creating Model Observer
You can create the new Observer class by the following command:
1 |
php artisan make:observer TestObserver --model=User |
and new class will created in your App/Observers directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php namespace App\Observers; use App\User; class TestObserver { public function created(User $user) { // } public function updated(User $user) { // } public function deleted(User $user) { // } } |
After that register the Observer by using the observe method on the Model you wish to observe and register it on boot method of your service provider.
1 2 3 4 |
public function boot() { Post::observe(TestObserver::class); } |
Hope it will be helpful for you. If you have any issue feel free to raise a ticket at https://bagisto.uvdesk.com/en/