您好,欢迎访问宜昌市隼壹珍商贸有限公司
400 890 5375在日常处理一些用户操作事件时,我们有时候需要记录下来,方便以后查阅,或者大数据统计。
Laravel 在模型事件中处理起来很方便:https://laravel-china.org/docs/laravel/5.5/eloquent#events
Laravel 的模型事件有两种方式,
dispatchesEvents属性映射事件类php artisan make:model Log
php artisan make:migration create_logs_table
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');
}
}php artisan migrate
php artisan make:provider ObserverLogServiceProvider
/config/app.php中的providers数组注册(大概如图中)
app目录下新建文件夹Observers存放模型观察器,并新建基类LogBaseServer并在构造函数构建基本属性(CLI是因为在命令行执行时不存在用户执行)
LogBaseServer(User模型,方法的名字要对应文档中的事件)
ObserverLogServiceProvider中运行

attach方法)1.在EventServiceProvider中的listen属性绑定好事件
2.事件PermissionRoleEvent中的注入两个参数,一个是角色,另一个是attach或者detach返回的数组
3.事件监听器PermissionRoleEventLog也继承基类LogBaseServer,这里就是根据传入的数组id遍历,然后创建日志
4.之后应用事件
1.在EventServiceProvider中的subscribe属性绑定好处理的类
2.事件监听类的方法
3.之后的效果就是这样了:
相关推荐:最新的五个Laravel视频教程