When dealing with some user operation events on a daily basis, we sometimes need to record them , for later reference or big data statistics.
Laravel is very convenient to handle in model events: https://laravel-china.org/docs/laravel/5.5/eloquent#events
Laravel’s model There are two ways of events,
- Setting
dispatchesEvents
Property mapping event class - Use observers to register events, here is the second one
- New model
php artisan make:model Log
Copy after login
- Create migration table:
php artisan make:migration create_logs_table
- The structure of the table is roughly like this, it can be designed as needed
engine = 'InnoDB'; $table->increments('id'); $table->string('user_id')->comment('操作人的ID'); $table->string('user_name')->comment('操作人的名字,方便直接查阅'); $table->string('url')->comment('当前操作的URL'); $table->string('method')->comment('当前操作的请求方法'); $table->string('event')->comment('当前操作的事件,create,update,delete'); $table->string('table')->comment('操作的表'); $table->string('description')->default(''); $table->timestamps(); }); DB::statement("ALTER TABLE `logs` comment '操作日志表'"); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('logs'); } }
- Run the migration to generate the table
php artisan migrate
- Create a new service provider to uniformly register all model event observers (the subsequent names can be more vivid)
php artisan make:provider ObserverLogServiceProvider
- to the
providers
array in/config/app.php
Register (roughly as shown in the picture)
-
##Create a new folder in the
- app
directory
ObserversStore model observers, and create a new base class
LogBaseServerand build basic attributes in the constructor (CLI is because there is no user execution when executing from the command line)
##Create a new observer inheriting the base class
-
LogBaseServer
- (
User
model, method The name should correspond to the event in the document)
##To the newly created service provider
ObserverLogServiceProvider-
Run in
Register events for the required models (I have quite a few, it will probably look like this in the future )
Then we trigger some events (addition, deletion and modification, the table data will be available)
##Many-to-many association insertion will not trigger the model (such as
attachMethod)
- At this time, you need to create a new event class to simulate (here is a rough introduction to assigning permissions to roles)
- EventServiceProvider
The attribute is bound to the event
2. Injection two in the eventPermissionRoleEventParameters, one is the role, the other is the array returned by
attachordetach
##
3. Event listenerPermissionRoleEventLog
also inherits the base classLogBaseServer
, here it is traversed according to the incoming array id, and then creates a log
4. Then apply the event
- Update Handle login and logout events gracefully
1. Bind thesubscribe
attribute inEventServiceProvider
to a well-handled class
2. Methods of the event listening class
3. After The effect is like this: