Sometimes we need to trigger an event after a table change, the most common for example, home page recommended item 1 changed, need to clear all home product cache.
First we need to create an observer class, such as App\Model\Observers\ProjectAttrObservers
, of course, where to place or what the name can be defined by itself.
The code inside might be
<?phpNamespaceApp\models\observersclass goodsobservers {public function saved (\app\models\goods $model ) {\cache:: Forget ( ' topgoodslist ' }} /span>
The effect is that when the goods
table is added and modified, saved
this method fires and then empties the cache
After AppServiceProvider
that, of course, you can also create a new example ObserverServiceProvider
.
<?phpNamespaceApp\providers;UseApp\models\goods;UseIlluminate\support\serviceprovider;ClassObserverserviceproviderExtendsServiceProvider{/** * Bootstrap any application services. * * @return void * *PublicfunctionBoot(){Goods::Observe (new \app\models\observers\goodsobservers ( /** * Register any application services. * @return void * /public function register< Span class= "token punctuation" > ({//}}
The purpose of this is to listen to the class at the end of the program when it is started, and it GoodsObservers
will be ObserverServiceProvider
placed in config/app.php
providers
an array.
This feature is only available within the Laravel program, and if other programs modify the goods table, the model watcher will not trigger.
How to use Model viewer in Laravel 5.1